1138 Postorder Traversal (25 分)
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 (≤ 50,000), 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
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
struct node{
int data;
struct node *lchild,*rchild;
};
vector<int> pre,in;
int flag = false;
void post(int pl,int pr,int il,int ir){
if(il > ir || flag )
return ;
int t = il;
while(pre[pl] != in[t]){
t++;
}
post(pl+1,pl+(t-il),il,t-1);
post(pl+(t-il)+1,pr,t+1,ir);
if(flag==false){
cout << in[il];
flag=true;
return ;
}
}
int main(){
struct node *root;
int n;
scanf("%d",&n);
for(int i = 0;i < n;i++){
int c;
cin >> c;
pre.push_back(c);
}
for(int i = 0;i < n;i++){
int c;
cin >> c;
in.push_back(c);
}
post(0,n-1,0,n-1);
return 0;
}
本文探讨了如何通过给定的前序和中序遍历序列,找到对应二叉树后序遍历的第一个元素。具体实现包括读取节点数量、前序和中序序列,使用递归算法构建二叉树,并输出后序遍历的首个元素。

被折叠的 条评论
为什么被折叠?



