Source:
Description:
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order 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 (≤), the total number of nodes in the binary tree. The second line gives the postorder 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 level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7 2 3 1 5 7 6 4 1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
Keys:
Code:
1 /* 2 time: 2019-06-30 14:40:45 3 problem: PAT_A1020#Tree Traversals 4 AC: 08:33 5 6 题目大意: 7 给出后序和中序遍历,打印层序遍历 8 */ 9 #include<cstdio> 10 #include<queue> 11 using namespace std; 12 const int M=35; 13 int post[M],in[M],n; 14 struct node 15 { 16 int data; 17 node *lchild,*rchild; 18 }; 19 20 node *Create(int postL, int postR, int inL, int inR) 21 { 22 if(postL > postR) 23 return NULL; 24 node *root = new node; 25 root->data = post[postR]; 26 int k; 27 for(k=inL; k<=inR; k++) 28 if(in[k] == post[postR]) 29 break; 30 int numLeft = k-inL; 31 root->lchild = Create(postL,postL+numLeft-1,inL,k-1); 32 root->rchild = Create(postL+numLeft,postR-1,k+1,inR); 33 return root; 34 } 35 36 void LayerOrder(node *root) 37 { 38 queue<node*> q; 39 q.push(root); 40 int pt=0; 41 while(!q.empty()) 42 { 43 root = q.front(); 44 q.pop(); 45 printf("%d%c", root->data, ++pt==n?‘\n‘:‘ ‘); 46 if(root->lchild) 47 q.push(root->lchild); 48 if(root->rchild) 49 q.push(root->rchild); 50 } 51 } 52 53 int main() 54 { 55 #ifdef ONLINE_JUDGE 56 #else 57 freopen("Test.txt", "r", stdin); 58 #endif // ONLINE_JUDGE 59 60 scanf("%d", &n); 61 for(int i=0; i<n; i++) 62 scanf("%d", &post[i]); 63 for(int i=0; i<n; i++) 64 scanf("%d", &in[i]); 65 node *root = Create(0,n-1,0,n-1); 66 LayerOrder(root); 67 68 return 0; 69 }
原文地址:https://www.cnblogs.com/blue-lin/p/11109732.html