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;
}
相关推荐
C^h1 天前
c++ string
开发语言·c++
raindayinrain1 天前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的1 天前
C++ 合并命名空间
开发语言·c++·网络安全
Zhao-Jichao1 天前
VS2026 打包 C++ 程序生成 EXE,借助 Installer Project 扩展工具
开发语言·c++
小徐不徐说1 天前
C++ 接口与插件设计:从工厂注册到 Qt 动态插件
数据库·c++·qt·系统架构·程序设计
大都督会赢的1 天前
C++第一节课
开发语言·c++
UIU1141 天前
P1233 [ICPC 2001 Taejon R] 木棍加工
数据结构·c++·算法·动态规划
TMedical1 天前
MedPlanning 截骨模拟矫形功能
c++·图像处理·人工智能·qt·健康医疗
qq_406981031 天前
共享变量一 关于extern与const
开发语言·c++
niyongsheng1 天前
3D 装箱算法工程化:数据结构、放置启发式与支撑规则
数据结构·算法·rust