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
二叉树建立,然后后序走一下就行
1 #include <bits/stdc++.h> 2 using namespace std; 3 int n,an[100005],bn[100005]; 4 struct Node{ 5 int val; 6 Node *left, *right; 7 }*head; 8 vector<int> v; 9 Node* build(int x,int ll, int rr){ 10 // cout <<ll<<" "<<rr<<endl; 11 int l = 0; 12 Node *root = (Node*)malloc(sizeof(Node)); 13 root->val = an[x]; 14 root->left = NULL; 15 root->right = NULL; 16 for(int i = ll ; i <= rr; i++){ 17 if(bn[i] == an[x]){ 18 l = i; 19 break; 20 } 21 } 22 if(l > ll){ 23 root->left = build( x+1, ll, l-1); 24 } 25 if(l < rr){ 26 root->right = build( x+1+l-ll, l+1, rr); 27 } 28 return root; 29 } 30 void search(Node *root){ 31 if(root){ 32 search(root->left); 33 search(root->right); 34 v.push_back(root->val); 35 } 36 } 37 int main(){ 38 cin >> n; 39 for(int i = 1; i <= n; i++) 40 cin >> an[i]; 41 for(int i = 1; i <= n; i++) 42 cin >> bn[i]; 43 head = build(1,1,n); 44 search(head); 45 cout << v[0]<<endl; 46 return 0; 47 }