当前位置:网站首页>L2-006 树的遍历(中后序确定二叉树&层序遍历)
L2-006 树的遍历(中后序确定二叉树&层序遍历)
2022-04-23 02:50:00 【S atur】

代码实现:
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N = 1e5+10;
int n, cnt;
int bk[N], md[N];
map<int, int> pos;
struct node{
int lson, rson, val;
}tree[N];
int build(int la, int lb, int ra, int rb){
int root = bk[rb];
int k = pos[root]; // 找到根节点在中序遍历中的index
if(la < k) tree[root].lson = build(la, k-1, ra, ra+k-la-1); // 递归左子树
if(lb > k) tree[root].rson = build(k+1, lb, ra+k-la, rb-1); // 递归右子树
return root;
}
void bfs(int root){
queue<int> q;
vector<int> ans;
q.push(root);
while(q.size()){
int t = q.front(); q.pop();
ans.push_back(t);
if(tree[t].lson) q.push(tree[t].lson);
if(tree[t].rson) q.push(tree[t].rson);
}
cout << ans[0];
for(int i = 1; i < ans.size(); i++) cout << " " << ans[i];
cout << endl;
}
signed main()
{
cin >> n;
for(int i = 1; i <= n; i ++) cin >> bk[i];
for(int i = 1; i <= n; i ++){
cin >> md[i];
pos[md[i]] = i;
}
int root = build(1, n, 1, n);
bfs(root);
return 0;
}
版权声明
本文为[S atur]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Satur9/article/details/124357191
边栏推荐
- 【Hcip】OSPF常用的6种LSA详解
- The problem of removing spaces from strings
- Renesas electronic MCU RT thread development and Design Competition
- Les derniers noeuds K de la liste jz22
- windows MySQL8 zip安装
- The usage of case when and select case when is very easy to use
- 魔王冷饭||#078 魔王答上海、南京行情;沟通指导;得国和打杀筛选;赚钱的目的;改变别人看法
- JDBC JDBC
- [unity3d] rolling barrage effect in live broadcasting room
- Suggestion: block reference sorting is in the order of keywords
猜你喜欢

JVM类加载器

How to build an integrated industrial Internet plus hazardous safety production management platform?

ROP Emporium x86_64 7~8题

高效音乐格式转换工具Music Converter Pro

The way to conquer C language

Flink stream processing engine system learning (III)

基于ele封装下拉菜单等组件

Specific field information of MySQL export table (detailed operation of Navicat client)

JVM runtime data area (I)

本地远程访问云服务器的jupyter
随机推荐
Microservices (distributed architecture)
期中汇总(概论+应用层+运输层)
Practice of industrial defect detection project (III) -- Based on FPN_ PCB defect detection of tensorflow
Planning code ROS migration POMDP prediction planning (I)
@Usage and difference between mapper and @ repository
基于Torchserve部署SBERT模型<语义相似度任务>
Modification du contenu de la recherche dans la boîte déroulante par PHP + MySQL
Shell script learning notes -- shell operation on files sed
基于Scrum进行创新和管理
How to solve the complexity of project document management?
Liunx foundation - zabbix5 0 monitoring system installation and deployment
Using go language to build web server
Target narak
C language 171 Number of recent palindromes
The express project changes the jade template to art template
JDBC JDBC
第46届ICPC亚洲区域赛(昆明) B Blocks(容斥+子集和DP+期望DP)
Intelligent agricultural management model
国产轻量级看板式Scrum敏捷项目管理工具
Codeforces round 784 (Div. 4) (a - H)