L2-006. 树的遍历
来源:互联网 发布:ubuntu切换root用户 编辑:程序博客网 时间:2024/05/16 23:47
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
集体思路:这是二叉树基本的已知中序和前序(后序)建树的类型,记住这个的模板就行,层序遍历用队列
#include<iostream>#include<cstdio>#include<vector>#include<queue>using namespace std;struct T{ int left; int right; };vector<int> ivec1,ivec2;struct T a[31];int build(int al,int ar,int bl ,int br);void print(int root);int main(void){int N,root,x; cin>>N; for(int i=0;i<N;i++) {cin>>x; ivec1.push_back(x); //后续 } for(int i=0;i<N;i++) { cin>>x; ivec2.push_back(x); //中序 } root =ivec1[N-1]; build(0,N-1,0,N-1); print(root);return 0;}//递归建树int build(int al,int ar,int bl ,int br) //a后续 b中序{ if(bl>br) return 0; int rt=ivec1[ar]; int p=bl; while(ivec2[p]!=rt) p++; int p2=p-bl; a[rt].left=build(al,al+p2-1,bl,p-1); a[rt].right=build(p2+al,ar-1,p+1,br); return rt;}//层序遍历void print(int root){ queue<int> q; vector<int> v; q.push(root); while(!q.empty()) { int w=q.front(); q.pop(); v.push_back(w); if(a[w].left!=0) q.push(a[w].left); if(a[w].right!=0) q.push(a[w].right); } int len=v.size(); for(int i=0;i<len;i++) { printf("%d%c",v[i],i==len-1?'\n':' '); } return ;}
0 0
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- Potential misconfiguration detected. Fix and restart Hue. 解决办法
- 超轻便的 Cache_Lite 文件缓存
- HC-05蓝牙模块配置方法
- 三层架构与MVC
- 说说自己对ssm整合的看法
- L2-006. 树的遍历
- 简单粗暴的实现背景图无限循环滚动
- Java基础知识之集合操作
- HDU5877 Weak Pair dfs + 线段树/树状数组 + 离散化
- 【剑指offer】请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 细数云计算产品和技术-OpenStack
- 统一设备模型(四):sysfs文件系统的分析
- 15-CoreData删除所有数据之NSBatchDeleteRequest
- 2016蓝桥杯C/C++省赛 交换瓶子(超级大水题)