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;
}
相关推荐
哥不想学算法28 分钟前
【C++】字符串字面量拼接
开发语言·c++
gugucoding3 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ChaoZiLL5 小时前
我的数据结构3——链表(link list)
数据结构·链表
cookies_s_s6 小时前
C++ 字符串动态创建对象 -- 工厂模式、自动注册、模板递归动态调用
服务器·开发语言·c++
王老师青少年编程6 小时前
2026年6月GESP真题及题解(C++七级):消消乐
数据结构·c++·算法·真题·gesp·2026年6月
海清河晏1116 小时前
数据结构 | 二叉搜索树
数据结构·c++·visual studio
盐焗鹌鹑蛋7 小时前
【C++】继承
开发语言·c++
Yang_jie_037 小时前
笔记:数据结构(顺序表)
数据结构·windows·笔记
会周易的程序员8 小时前
使用 pybind11 封装 C++ 日志库 microLog 为 Python 模块
java·c++·python·物联网·架构·日志·aiot
WZF-Sang8 小时前
网络基础——2
服务器·网络·c++·学习·网络编程·php