A1020. Tree Traversals
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 (<=30), 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
1 #include<cstdio> 2 #include<iostream> 3 #include<queue> 4 using namespace std; 5 typedef struct NODE{ 6 struct NODE* lchild, *rchild; 7 int data; 8 }node; 9 int in[31], post[31]; 10 int N; 11 node* create(int inL, int inR, int postL, int postR){ 12 if(postL > postR){ 13 return NULL; 14 } 15 int head = postR; 16 node * root = new node; 17 root->data = post[head]; 18 int i; 19 for(i = inL; i <= inR; i++){ 20 if(in[i] == post[head]) 21 break; 22 } 23 int numL = i - inL; 24 root->lchild = create(inL, i - 1, postL, postL + numL - 1); 25 root->rchild = create(i + 1, inR, postL + numL, postR - 1); 26 return root; 27 } 28 void levelOrder(node* tree){ 29 queue<node*> Q; 30 Q.push(tree); 31 node* temp; 32 int cnt = 0; 33 while(Q.empty() == false){ 34 temp = Q.front(); 35 cnt++; 36 Q.pop(); 37 printf("%d", temp->data); 38 if(cnt != N) 39 printf(" "); 40 if(temp->lchild != NULL) 41 Q.push(temp->lchild); 42 if(temp->rchild != NULL) 43 Q.push(temp->rchild); 44 } 45 } 46 int main(){ 47 scanf("%d", &N); 48 for(int i = 0; i < N; i++) 49 scanf("%d", &post[i]); 50 for(int i = 0; i < N; i++) 51 scanf("%d", &in[i]); 52 node* tree = create(0, N - 1, 0, N - 1); 53 levelOrder(tree); 54 cin >> N; 55 return 0; 56 }
总结:
1、题意:给出后序遍历和中序遍历,求层序遍历。
2、层序遍历时不要忘记在访问完元素后pop。
3、创建二叉树结束的条件是后序遍历的区间为空(postL > postR)。
4、注意控制最后一个空格不要输出,可以设置一个计数器,为N时不输出空格。