PAT 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. 输入格式: 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.
输出格式: For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.
输入样例:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
输出样例:
3
题目分析:模板题,根据中序遍历和前序遍历求解后序遍历序列的第一个元素。
注意:应该牢牢掌握以下三种二叉树的重构。 1.前序+中序 2.中序+后序 3.中序+层序
AC代码:
#include <iostream>
using namespace std;
const int maxn = 50010;
int mid[maxn] = {0};
int pre[maxn] = {0};
int post[maxn] = {0};
int n, idx=1;
struct node{
int data;
node* lchild;
node* rchild;
};
node* build(int preL, int preR, int inL, int inR){
if(preL > preR)return NULL;
node* root = new node;
root->data = pre[preL];
int k;
for(k = inL; k<=inR; ++k){
if(mid[k] == pre[preL])
break;
}
int numLeft = k - inL;
root->lchild = build(preL+1, preL+numLeft, inL, k-1);
root->rchild = build(preL+numLeft+1, preR, k+1, inR);
return root;
}
void postorder(node* root){
if(root){
postorder(root->lchild);
postorder(root->rchild);
post[idx ++] = root->data;
}
}
int main(){
scanf("%d", &n);
for(int i=1; i<=n; ++i){scanf("%d", &pre[i]);}
for(int i=1; i<=n; ++i){scanf("%d", &mid[i]);}
node* root = build(1, n, 1, n);
postorder(root);
cout<<post[1]<<endl;
return 0;
}