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 (<=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 6Sample Output:
3
我好奇我现在写的和考试的时候写的一样,为什么考试的时候最后一点超时呢。。。
#include<stdio.h>
#include<stdlib.h>
int pre[50010],in[50010];
typedef struct Node *node;
struct Node{
int x;
node left;
node right;
};
node build(int s1,int e1,int s2,int e2){
node T=(node)malloc(sizeof(struct Node));
T->x=pre[s1];
T->left=T->right=0;
int root,i;
for(i=s2;i<=e2;i++){
if(in[i]==pre[s1]){
root=i;break;
}
}
if(root!=s2){
T->left=build(s1+1,s1+root-s2,s2,root-1);
}
if(root!=e2){
T->right=build(s1+root-s2+1,e1,root+1,e2);
}
return T;
}
void postorder(node T){
if(T){
postorder(T->left);
postorder(T->right);
printf("%d",T->x);exit(0);
}
}
int main(){
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&pre[i]);
}
for(i=0;i<n;i++){
scanf("%d",&in[i]);
}
node T=0;
T=build(0,n-1,0,n-1);
postorder(T);
}
#include<stdio.h>
#include<stdlib.h>
int pre[50010],in[50010];
typedef struct Node *node;
struct Node{
int x;
node left;
node right;
};
node build(int s1,int e1,int s2,int e2){
if(s1==e1){
printf("%d",pre[s1]);exit(0);
}
node T=(node)malloc(sizeof(struct Node));
T->x=pre[s1];
T->left=T->right=0;
int root,i;
for(i=s2;i<=e2;i++){
if(in[i]==pre[s1]){
root=i;break;
}
}
if(root!=s2){
T->left=build(s1+1,s1+root-s2,s2,root-1);
}
if(root!=e2){
T->right=build(s1+root-s2+1,e1,root+1,e2);
}
return T;
}
//void postorder(node T){
// if(T){
// postorder(T->left);
// postorder(T->right);
// printf("%d",T->x);exit(0);
// }
//}
int main(){
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&pre[i]);
}
for(i=0;i<n;i++){
scanf("%d",&in[i]);
}
node T=0;
T=build(0,n-1,0,n-1);
// postorder(T);
}