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;
}
相关推荐
哈里谢顿13 小时前
跳表(Skip List):简单高效的有序数据结构
数据结构
xlp666hub18 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网20 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub1 天前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星1 天前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub2 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
任沫2 天前
字符串
数据结构·后端
不想写代码的星星2 天前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
祈安_2 天前
Java实现循环队列、栈实现队列、队列实现栈
java·数据结构·算法
不想写代码的星星3 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++