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;
}
相关推荐
科大饭桶1 小时前
数据结构自学Day5--链表知识总结
数据结构·算法·leetcode·链表·c
小高Baby@1 小时前
map数据结构在Golang中是无序的,并且键值对的查找效率较高的原因
数据结构
北风toto1 小时前
python学习DataFrame数据结构
数据结构·python·学习
mit6.8241 小时前
[Meetily后端框架] Whisper转录服务器 | 后端服务管理脚本
c++·人工智能·后端·python
L_autinue_Star3 小时前
手写vector容器:C++模板实战指南(从0到1掌握泛型编程)
java·c语言·开发语言·c++·学习·stl
怀旧,3 小时前
【数据结构】8. 二叉树
c语言·数据结构·算法
凤年徐4 小时前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题
无小道5 小时前
c++--typedef和#define的用法及区别
c语言·开发语言·汇编·c++
mit6.8246 小时前
[Vroom] 位置与矩阵 | 路由集成 | 抽象,解耦与通信
c++·人工智能·算法