当前位置:网站首页>玩转二叉树 (25 分)
玩转二叉树 (25 分)
2022-04-23 08:35:00 【怀化第二深情】
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
#include<bits/stdc++.h>
using namespace std;
const int N=40;
map<int,int>l,r,pos;
int post[N],in[N];
int n,cnt;
int build(int il,int ir,int pl,int pr){
int root=post[pl];
int k=pos[root];
if(il<k)l[root]=build(il,k-1,pl+1,pl+k-il);
if(ir>k)r[root]=build(k+1,ir,pl+k-il+1,pr);
return root;
}
void bfs(int root) //BFS用来层序遍历输出
{
queue<int> q;
q.push(root);
while (q.size())
{
auto t = q.front();
q.pop();
if(cnt==0)cout<<t;
else cout <<" "<<t;
cnt++;
if (r.count(t)) q.push(r[t]); //存在则加入队列,等待下一层遍历
if (l.count(t)) q.push(l[t]); //判断该节点的左右儿子是否存在
}
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>in[i];
pos[in[i]]=i;
}
for(int i=0;i<n;i++)cin>>post[i];
int root=build(0,n-1,0,n-1);
bfs(root);
return 0;
}
版权声明
本文为[怀化第二深情]所创,转载请带上原文链接,感谢
https://blog.csdn.net/dege2929512534/article/details/124340070
边栏推荐
- Failed to prepare device for development
- form表单 post提交 数据量大的问题
- Reference passing 1
- 第一性原理 思维导图
- HAL库的RCC简介
- Large amount of data submitted by form post
- PgSQL wants to implement all kinds of column sub query operations of MySQL
- idea底栏打开services
- Qtablewidget header customization and beautification developed by pyqt5 (with source code download)
- 扣缴义务人
猜你喜欢

洋桃电子STM32物联网入门30步笔记一、HAL库和标准库的区别

00后最关注的职业:公务员排第二,第一是?

DJ音乐管理软件Pioneer DJ rekordbox

Yangtao electronic STM32 Internet of things introduction 30 steps notes 1. The difference between Hal library and standard library

ATSS(CVPR2020)

flask项目跨域拦截处理以及dbm数据库学习【包头文创网站开发】

Get the absolute path of the class according to the bytecode

Notes on 30 steps of introduction to the Internet of things of yangtao electronics STM32 III. cubemx graphical programming and setting the IO port on the development board

Shell脚本进阶

Idea import commons-logging-1.2 Jar package
随机推荐
Go语言自学系列 | golang结构体指针
Transformer XL: attention language modelsbbeyond a fixed length context paper summary
Copy array in JS
How much inventory recording does the intelligent system of external call system of okcc call center need?
ESP32程序下载失败,提示超时
RPC过程
汇编语言与逆向工程 栈溢出漏洞逆向分析实验报告
Idea import commons-logging-1.2 Jar package
Goland 调试go使用-大白记录
Notes on 30 steps of introduction to the Internet of things of yangtao electronics STM32 III. cubemx graphical programming and setting the IO port on the development board
idea底栏打开services
请问中衍期货安全靠谱吗?
DOM 学习之—添加+-按钮
线程的调度(优先级)
【深度好文】Flink SQL流批⼀体化技术详解(一)
IDEA导入commons-logging-1.2.jar包
Virtual online exhibition - Online VR exhibition hall realizes 24h immersive exhibition viewing
Input / output system
Get the absolute path of the class according to the bytecode
How browser works