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 分钟前
深入学习cpp初阶模板
开发语言·c++·学习
菜鸟丁小真8 分钟前
LeetCode hot100-287.寻找重复数和994.腐烂的橘子
数据结构·算法·leetcode·知识点总结
老四啊laosi14 分钟前
[C++进阶] 25. C++11新特性(一)
c++·c++11·右值
零号全栈寒江独钓36 分钟前
基于c/c++实现linux/windows跨平台ntp时间戳服务器
linux·c语言·c++·windows
笨鸟先飞的橘猫38 分钟前
数据结构学习——跳表
数据结构·python·学习
ulias21241 分钟前
进程初识(1)
linux·运维·服务器·网络·c++
t***54442 分钟前
Orwell Dev-C++ 和 Embarcadero Dev-C++ 哪个更好
开发语言·c++
BestOrNothing_20151 小时前
C++零基础到工程实战(4.3.4):vector数组搜索、删除、插入与排序
c++·vector·sort·find·insert·动态数组·erase
Pentane.1 小时前
【力扣hot100】【Leetcode 15】三数之和|暴力枚举 双指针 算法笔记及打卡(14/100)
数据结构·笔记·算法·leetcode
Mr_pyx1 小时前
【LeetCode Hot 100】 - 缺失的第一个正数完全题解
数据结构·算法