当前位置:网站首页>根据后序和中序遍历输出先序遍历 (25 分)
根据后序和中序遍历输出先序遍历 (25 分)
2022-04-23 08:35:00 【怀化第二深情】
本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。
输出格式:
在一行中输出Preorder: 以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
Preorder: 4 1 3 2 6 5 7
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include<map>
using namespace std;
const int N = 40;
int n,count1;
int postorder[N], inorder[N]; //前序遍历,中序遍历
unordered_map<int, int> l, r, pos; //用哈希表模拟二叉树
int build(int il, int ir, int pl, int pr)
{
int root = postorder[pr];
int k = pos[root]; //得到根节点在中序遍历中的下标
//k大于il表示根节点左边还有节点,即当前根节点存在左子树,下同
//下面两行是难点,举例解释见图
if (il < k) l[root] = build(il, k - 1, pl, pl + k - 1 - il);
if (ir > k) r[root] = build(k + 1, ir, pl + k - il, pr - 1);
return root;
}
void dfs(int root) //BFS用来层序遍历输出
{
if(count1==0)
cout<<root;
else cout<<" "<<root;
count1++;
if(l.count(root))dfs(l[root]);
if(r.count(root))dfs(r[root]);
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ ) cin >> postorder[i];
for (int i = 0; i < n; i ++ )
{
cin >> inorder[i];
pos[inorder[i]] = i; //记录中序遍历每个点位置(剪枝)
}
int root = build(0, n - 1, 0, n - 1); //参数为中序遍历区间和后序遍历区间
printf("Preorder: ");
dfs(root);
return 0;
}
版权声明
本文为[怀化第二深情]所创,转载请带上原文链接,感谢
https://blog.csdn.net/dege2929512534/article/details/124340031
边栏推荐
- 求简单类型的矩阵和
- Using qlst excel file
- 面了一圈,整理了这套面试题。。
- Detailed description of self feeling of auricular point weight loss 0422
- 《深度学习》学习笔记(八)
- idea底栏打开services
- Anonymous type (c Guide Basics)
- Type anonyme (Principes fondamentaux du Guide c)
- STM32F103ZET6【标准库函数开发】----库函数介绍
- SYS_ CONNECT_ BY_ Path (column, 'char') combined with start with connect by prior
猜你喜欢

Asan minimalism

idea配置连接远程数据库MySQL,或者是Navicat连接远程数据库失败问题(已解决)

After a circle, I sorted out this set of interview questions..

四张图弄懂matplotlib的一些基本用法

正点原子携手OneOS直播 OneOS系统教程全面上线

引用传递1

Shell script advanced

经典题目刷一刷

ATSS(CVPR2020)

STM32 uses Hal library. The overall structure and function principle are introduced
随机推荐
K210学习笔记(二) K210与STM32进行串口通信
Go语言自学系列 | golang结构体的初始化
【精品】利用动态代理实现事务统一管理 二
Detailed description of self feeling of auricular point weight loss 0422
PDF with watermark
Stm32f103zet6 [development of standard library functions] - Introduction to library functions
Yangtao electronic STM32 Internet of things entry 30 step notes IV. engineering compilation and download
Word plus watermark
Go语言自学系列 | golang结构体指针
Overview of bus structure
Star Trek强势来袭 开启元宇宙虚拟与现实的梦幻联动
ESP32程序下载失败,提示超时
Excle plus watermark
swagger文档导出自定义v2/api-docs拦截
Transformer XL: attention language modelsbbeyond a fixed length context paper summary
LINQ学习系列-----1.4 匿名对象
php基于哈希算法出现的强弱比较漏洞
应纳税所得额
jsp页面编码
LeetCode396.旋转数组