1020. Tree Traversals (25)
来源:互联网 发布:excel数据共享 编辑:程序博客网 时间:2024/06/11 23:33
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
提交代码
解题思路:
不管是左右子树还是整棵树,后序遍历的最后一个元素就是根节点,然后从中序遍历中找到根节点在中序遍历的位置,并且记录左子树元素的个数。
中序遍历中根节点以前的位左子树,以后的位右子树,然后递归遍建立左右子树,如果子树为空则返回0,l>r的情况就是子树为空的情况。在根据根节点输出层序遍历就可以了。
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; #define N 35 int last[N],in[N]; struct node{ int left; int right; }tree[N]; int n,cnt; int build(int l1,int r1,int l2,int r2){ int root; if(l1 <= r1&&l2 <= r2){ root = last[r2]; int cnt = 0; int index; for(index = l1;in[index] != root;index++,cnt++);//判定根节点下标和确定左子树的元素个数 tree[root].left = build(l1,index-1,l2,l2+cnt-1);//建立左子树 tree[root].right = build(index+1,r1,l2+cnt,r2-1);//建立右子树 }else{ return 0; } return root; } void print(int root){ queue<int>q; q.push(root);//根节点入队 while(!q.empty()){ int temp = q.front(); cnt++; printf("%d",temp);//输出结点 if(cnt != n){ printf(" "); }else{ printf("\n"); } q.pop(); if(tree[temp].left){ q.push(tree[temp].left);//左子树如队列 } if(tree[temp].right){ q.push(tree[temp].right);//右子树入队列 } } } int main(){ // freopen("input.txt","r",stdin); scanf("%d",&n); for(int i = 1;i <= n;i++){ scanf("%d",&last[i]); } for(int i = 1;i <= n;i++){ scanf("%d",&in[i]); } int root = build(1,n,1,n); print(root); return 0; }
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 1020. Tree Traversals (25)
- 【已解决】scrapy 报错 no module named win32api 的解决方案
- 一个简单的类的创建
- 01Python基础语法
- ccf 图像旋转
- vs2015常用快捷键总结
- 1020. Tree Traversals (25)
- BZOJ[2157]旅游 树链剖分+线段树
- c++程序入门(一)——指针
- 关于KS系列Android开发学习总结
- SEON
- webpack3.x文件配置
- 图像滤波处理:均值、中值滤波器实现
- 微信小程序处理用户拒绝授权情况及微信登录,登录保存等系列解决方案
- 数据结构 之 线性表中的顺序表