HLG 2040 binary tree traversal (transformation between binary tree traversal)

Source: Internet
Author: User

 

Returns the central and forward traversal of a binary tree, and outputs its post-order traversal.

Input

There are multiple groups of data in this question, and the input is processed until the end of the file.

The first row of each data group contains an integer n, indicating that this binary tree has a total of n nodes.

Each row in the next row contains n integers, indicating the ordinal traversal of the tree.

Each row in the next row contains n integers, indicating the forward traversal of the tree.

3 <= n <= 100

Output

Each group of outputs contains a row, indicating the post-order traversal of the tree.

Sample Input

7
4 2 5 1 6 3 7
1 2 4 5 3 6 7

Sample Output

4 5 2 6 7 3 1
 

 

The Code is as follows:

 

#include 
 
  #include 
  
   #include 
   
    #include 
    
     #define MAXN 10005#define RST(N)memset(N, 0, sizeof(N))using namespace std;int inorder_table[MAXN];int preorder_table[MAXN];int position[MAXN], n;void work( int in_l, int in_r, int pre_l, int pre_r){int pos;if(in_l == in_r) {cout << inorder_table[in_l] << ' ';return;}pos = position[preorder_table[pre_l]];if(in_l <= ( pos - 1)) work(in_l, pos-1, pre_l+1, pos-in_l+pre_l);if((pos + 1) <= in_r) work(pos+1, in_r, pre_r-in_r+pos+1, pre_r);cout << inorder_table[pos] << ' ';}int main(){while(cin >> n) {        RST(inorder_table), RST(preorder_table), RST(position);for(int i=1; i<=n; i++) {cin >> inorder_table[i];position[inorder_table[i]] = i;}for(int i=1; i<=n; i++) cin >> preorder_table[i];work(1, n, 1, n);cout << endl;}return 0;}
    
   
  
 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.