文章目录
Author: CHEN, Yue
Organization: 浙江大学
Time Limit: 650 ms
Memory Limit: 64 MB
Code Size Limit: 16 KB
A1138 Postorder Traversal (25point(s))
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
Code
#include <bits/stdc++.h>
using namespace std;
struct NODE{
int data;
struct NODE *lchild,*rchild;
};
vector<int> pre,in,post;
void postorder(NODE *root){
if(root==NULL) return;
postorder(root->lchild);
postorder(root->rchild);
post.push_back(root->data);
}
NODE *build(int preL, int preR,int inL,int inR){
if(preL>preR) return NULL;
NODE *root = new NODE;
root->data=pre[preL];
int i;
for(i=inL;i<=inR;i++){
if(pre[preL]==in[i])
break;
}
int lcnt=i-inL;
root->lchild=build(preL+1,preL+lcnt,inL,i-1);
root->rchild=build(preL+lcnt+1,preR,i+1,inR);
return root;
}
int main(){
int n;
scanf("%d",&n);
pre.resize(n);
in.resize(n);
for(int i=1;i<=n;i++) scanf("%d",&pre[i]);
for(int i=1;i<=n;i++) scanf("%d",&in[i]);
NODE *root = build(1,n,1,n);
postorder(root);
printf("%d\n",post[0]);
return 0;
}
Analysis
-给出先序和中序,求后序遍历的第一个结点的值。