pat甲1020. Tree Traversals(已知后序和中序求层次遍历)
来源:互联网 发布:python unpack修饰符 编辑:程序博客网 时间:2024/05/29 04:45
1020. Tree Traversals (25)
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:72 3 1 5 7 6 41 2 3 4 5 6 7Sample Output:
4 1 6 3 5 7 2
tips:递归建树,广搜输出层次遍历
#include<iostream>#include<queue>using namespace std;int rt,n;int t[320][2];//模拟建树int post[320];//后序int in[302];//中序int flag;queue<int>q;void build(int &x,int l,int r,int ll,int rr){if(l>r)return;x=post[r];int index;for(int i=ll;i<=rr;i++){if(in[i]==x){index=i;break;}}build(t[x][0],l,l+index-1-ll,ll,index-1);build(t[x][1],l+index-ll,r-1,index+1,rr);}void level_traversal(int x){q.push(x);while(!q.empty()){int tt=q.front();q.pop();printf("%s%d",flag==0?"":" ",tt);flag=1;if(t[tt][0])q.push(t[tt][0]);if(t[tt][1])q.push(t[tt][1]);}}int main(){cin>>n;for(int i=1;i<=n;i++)cin>>post[i];for(int i=1;i<=n;i++)cin>>in[i];build(rt,1,n,1,n);//cout<<rt<<endl;level_traversal(rt);return 0;}
- pat甲1020. Tree Traversals(已知后序和中序求层次遍历)
- pat甲1119. Pre- and Post-order Traversals (已知前序和后序遍历求中序遍历)
- 1020. Tree Traversals (25)已知后序中序 层次遍历
- PAT 1020. Tree Traversals (25)(树的构造与遍历,通过后序中序输出层次遍历)
- 1020. Tree Traversals (25) - 已知后序和中序(前序和中序)求二叉树 (pat leetcode)
- PAT A 1020. Tree Traversals (25) 由两个遍历序列得层次遍历序列
- pat 甲1127. ZigZagging on a Tree (已知后序及中序建树,并层次往返输出)
- 【PAT】1020. Tree Traversals
- PAT 1020. Tree Traversals
- PAT 1020. Tree Traversals
- PAT--1020. Tree Traversals
- PAT 1020. Tree Traversals
- PAT 1020. Tree Traversals
- 【PAT】1020. Tree Traversals
- PAT 甲级 1020 Tree Traversals (二叉树遍历)
- 树的遍历-已知中序+(前序|后序)求层次遍历
- PAT 1020. Tree Traversals (25) 根据树的中序与后序,求层序
- pat 1020. Tree Traversals (25)
- 算法学习 2
- Chrome安装ARC Welder
- 线程与异常
- POJ 1703 Find them, Catch them 笔记
- manacher算法
- pat甲1020. Tree Traversals(已知后序和中序求层次遍历)
- 高仿微信5.2.1主界面及消息提醒
- Android这交互炸了:饿了么是怎么让Image变成详情页的
- vue.js 开发环境搭建最简单攻略
- 【kuangbin带你飞】之搜索 poj3278
- golang中使用package json遇到的问题
- 2016.12.03【初中部 NOIP提高C组】模拟赛题解
- kernel rpm包的制作
- spring mvc传入json返回modelAndView