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;
}
相关推荐
Controller-Inversion8 小时前
42. 接雨水
数据结构·算法·leetcode
Controller-Inversion8 小时前
33. 搜索旋转排序数组
数据结构·算法·leetcode
￰meteor8 小时前
【移动语义与移动构造】
c++
li星野8 小时前
二分查找六题通关:从标准模板到旋转数组(Python + C++)
java·c++·python
宵时待雨9 小时前
优选算法专题6:模拟
数据结构·c++·算法·leetcode·职场和发展
Liangwei Lin9 小时前
LeetCode 35. 搜索插入位置
数据结构·算法·leetcode
H Journey9 小时前
C++性能优化
c++·性能优化
叼烟扛炮9 小时前
C++ 知识点19 匿名对象
开发语言·c++·算法·匿名对象
叼烟扛炮9 小时前
C++ 知识点23 类模板
开发语言·c++·算法·类模版
邪修king9 小时前
C++ 继承超全详解:核心语法、作用域、默认函数、菱形继承与避坑指南
c语言·c++