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
1 #include <stdio.h> 2 #include <iostream> 3 const int maxn=50010; 4 struct node{ 5 int data; 6 node* left,*right; 7 }; 8 int in[maxn],pre[maxn]; 9 node* create(int prel,int prer,int inl,int inr){ 10 if(prel>prer) return NULL; 11 node* root = new node; 12 root->data = pre[prel]; 13 int k; 14 for(k=inl;k<=inr;k++){ 15 if(in[k]==pre[prel]) break; 16 } 17 int numleft = k-inl; 18 root->left = create(prel+1,prel+numleft,inl,k-1); 19 root->right = create(prel+numleft+1,prer,k+1,inr); 20 return root; 21 } 22 int main(){ 23 int n; 24 scanf("%d",&n); 25 for(int i=0;i<n;i++){ 26 int d; 27 scanf("%d",&d); 28 pre[i]=d; 29 } 30 for(int i=0;i<n;i++){ 31 int d; 32 scanf("%d",&d); 33 in[i]=d; 34 } 35 int prel=0,prer=n-1,inl=0,inr=n-1; 36 int numleft=n; 37 int k; 38 while(numleft!=1){ 39 for(k=inl;k<=inr;k++){ 40 if(in[k]==pre[prel]) break; 41 } 42 int nl=k-inl; 43 int nr=inr-k; 44 if(nl==0){ 45 prel=prel+nl+1; 46 prer=prer; 47 inl=k+1; 48 inr=inr; 49 numleft=nr; 50 } 51 else{ 52 prel=prel+1; 53 prer=prel+nl; 54 inl=inl; 55 inr=k-1; 56 numleft=nl; 57 } 58 } 59 printf("%d",in[inl]); 60 }
注意点:这道题虽然给的时间很多650ms,但直接建树再查找还是会超时,好像可以用引用来避免超时。
不建树其实就是通过两个序列来找到第一个叶子节点,当一个节点的左边或右边只有一个元素时,剩下的那个元素就是要输出的值。