1364:二叉树遍历(flist)

【算法分析】

递归 构造子树的中序遍历序列和层次遍历序列

层次遍历序列第一个元素,一定是整棵树的根结点。在中序遍历序列中找到该根结点元素,其左边就是左子树的中序遍历序列,右边就是右子树的中序遍历序列。接下来我们需要构造左右子树的层次遍历序列。

【参考代码】

复制代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
string in,level;//int中序遍历 level层序遍历
void preorder(int l1,int r1,int l2,int r2){
	int pos;
	for(int i=l2;i<=r2;i++){
		int flag=0;
		for(int j=l1;j<=r1;j++){
			if(level[i]==in[j]){//找根
				cout<<in[j];
				pos=j;
				flag=1;
				break;
			}
		}
		if(flag) break;
	}
	if(pos>l1) preorder(l1,pos-1,l2,r2);
	if(pos<r1) preorder(pos+1,r1,l2,r2);
}
int main()
{
	cin>>in>>level;
	preorder(0,in.length()-1,0,level.length()-1);	
    return 0;
}
相关推荐
郝学胜-神的一滴1 小时前
中级OpenGL教程 022:探秘三维世界的血脉传承——物体父子关系与矩阵递归奥义
c++·线性代数·unity·矩阵·游戏引擎·unreal engine·opengl
拂拉氏1 小时前
【知识讲解】 链式哈希表的实现与unordered_map和unordered_set的封装
数据结构·哈希算法·散列表
haolin123.1 小时前
数据结构--二叉树
数据结构
不如语冰1 小时前
AI大模型入门-参数的传递
数据结构·人工智能·pytorch·python
ch0sen1pm1 小时前
刚学完 CAS 原子操作,我花了一晚上写了三个无锁队列
c++
qeen871 小时前
【C++】vector的模拟实现详解(二)
c++·学习·算法·迭代器·stl
流浪0012 小时前
数据结构篇(四):线性表——链表——双链表
数据结构·链表
j7~2 小时前
【C++】C++ 继承全解析:从基本语法到菱形继承的底层原理
开发语言·c++·继承·组合·虚继承·#暑假·七月创作之星博客挑战赛
数行拙笔2 小时前
C++客户端---String类型
开发语言·c++·bootstrap
草莓熊Lotso2 小时前
【Linux网络】深入理解Linux IO多路复用:从本质到select服务器实战
linux·运维·服务器·c语言·网络·数据库·c++