- Postorder Traversal (25)
时间限制
600 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder 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 (<=50000), the total number of nodes in the binary tree. The second line gives the preorder 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 first number of the postorder traversal sequence of the corresponding binary tree.
Sample Input:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
Sample Output:
3
这个题,真正看出我写代码的能力,老师讲过的,只是没讲怎么实现,自己就不会实现了,太菜了。。。
已知前序和中序求后序;
可根据思路:第一步:根据前序可知根节点为1;第二步:根据中序可知2 3为根节点1的左子树和5 4 7 6为根节点1的右子树;第三步:递归实现,把2 3当做新的一棵树和5 4 7 6也当做新的一棵树;第四步:在递归的过程中输出后序。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 50004;
int a[N],b[N];
int n;
bool flag = false;
//递归地分左子树和右子树,p为前序遍历的起始点
//p代表的是该子树的前序起点,q代表的是中序起点,m代表的是子树的长度
void dfs(int p,int q,int m)
{
/*if(flag){
return;
}*/
//这儿是输出叶子节点
if(m == 1){
printf("%d ",a[p]);
/*flag = true;*/
return;
}
if(m <= 0){
return ;
}
int root = q;
for(int i = q;i <= q + m;++i)
{
if(a[p] == b[i]){
root = i;
break;
}
}
// << p << " " << root << endl;
//cout << p + 1 << " " << q << " " << root - q << endl;
//cout << p + root - q + 1 << " " << q + root - q + 1 << " " << m - root + q - 1 << endl;
dfs(p + 1,q,root - q);
dfs(p + root - q + 1,q + root - q + 1,m - root + q - 1);
//这儿输出根节点
printf("%d ",a[p]);
}
int main()
{
scanf("%d",&n);
for(int i = 0;i < n;++i)
{
scanf("%d",&a[i]);
}
for(int i = 0;i < n;++i)
{
scanf("%d",&b[i]);
}
dfs(0,0,n);
return 0;
}