博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
L2-006. 树的遍历
阅读量:4113 次
发布时间:2019-05-25

本文共 1140 字,大约阅读时间需要 3 分钟。

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:
72 3 1 5 7 6 41 2 3 4 5 6 7
输出样例:

4 1 6 3 5 7 2

思路:根据树的后序和中序建树,找出节点的左右子树,用数组保存,注意一定不要把边界写错,在bfs进行中序遍历树。

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;const int maxn=50;int lch[maxn],rch[maxn],in_order[maxn],past_order[maxn];int Build(int l1,int r1,int l2,int r2){ if(l1>r1) return 0; int p1=l1; int root=past_order[r2]; while(in_order[p1]!=root) p1++; int cnt=p1-l1; lch[root]=Build(l1,p1-1,l2,l2+cnt-1); rch[root]=Build(p1+1,r1,l2+cnt,r2-1); return root;}vector
ans;void dfs(int x){ queue
p; p.push(x); ans.push_back(x); while(!p.empty()) { int u=p.front(); p.pop(); if(lch[u]) { ans.push_back(lch[u]); p.push(lch[u]); } if(rch[u]) { ans.push_back(rch[u]); p.push(rch[u]); } }}int main(){ int n; cin>>n; for(int i=0; i
>past_order[i]; for(int i=0; i
>in_order[i]; Build(0,n-1,0,n-1); dfs(past_order[n-1]); for(int i=0; i

转载地址:http://ofgsi.baihongyu.com/

你可能感兴趣的文章
「译」在 python 中,如果 x 是 list,为什么 x += "ha" 可以运行,而 x = x + "ha" 却抛出异常呢?...
查看>>
谷歌阅读器将于2013年7月1日停止服务,博客订阅转移到邮箱
查看>>
浅谈JavaScript的语言特性
查看>>
LeetCode第39题思悟——组合总和(combination-sum)
查看>>
LeetCode第43题思悟——字符串相乘(multiply-strings)
查看>>
LeetCode第44题思悟——通配符匹配(wildcard-matching)
查看>>
LeetCode第45题思悟——跳跃游戏(jump-game-ii)
查看>>
LeetCode第46题思悟——全排列(permutations)
查看>>
LeetCode第47题思悟—— 全排列 II(permutations-ii)
查看>>
LeetCode第48题思悟——旋转图像(rotate-image)
查看>>
驱动力3.0,动力全开~
查看>>
记CSDN访问量10万+
查看>>
Linux下Oracle数据库账户被锁:the account is locked问题的解决
查看>>
记CSDN访问20万+
查看>>
Windows 环境下Webstorm 2020.3 版本在右下角找不到Git分支切换部件的一种解决方法
查看>>
Electron-Vue项目中遇到fs.rm is not a function问题的解决过程
查看>>
飞机换乘次数最少问题的两种解决方案
查看>>
有向无回路图的理解
查看>>
设计模式中英文汇总分类
查看>>
WPF实现蜘蛛纸牌游戏
查看>>