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;
}
相关推荐
夜悊3 小时前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴4 小时前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt00118 小时前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
小小工匠21 小时前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
玖玥拾1 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you1 天前
constexpr函数
c++
Qres8211 天前
算法复键——树状数组
数据结构·算法
凡人叶枫1 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫1 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss1 天前
BRpc使用
c++·rpc