Suppose the keys in a binary tree is distinct positive integers. Given the Postorder and inorder traversal sequences, you is supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains the one test case. For each case, the first line gives a positive integer N (<=30) and 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 is separated by a space.
Output Specification:
For each test case, the print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must is separated by exactly one space, and there must is no extra space at the end of the line.
Sample Input:
72 3 1 5 7 6 41 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
Thought: The sequence of the sequence and then the hierarchy of sequential traversal is very simple problem. It took a long time because of punctuation, and if it was followed by a punctuation mark.
1#include <cstdio>2#include <cstring>3#include <queue>4#include <algorithm>5 using namespacestd;6 Const intmaxn= -;7 structnode8 {9 intdata;TenNode *Lchild; OneNode *Rchild; A }; - int inch[MAXN],POST[MAXN]; - intN; theNode * Create (intPostl,intPOSTR,intInL,intInR) - { - if(postl>postr) - returnNULL; +Node *root=Newnode; -Root->data=Post[postr]; + intK; A for(k=inl;k<=inr;k++) at { - if(inch[k]==Post[postr]) - { - Break; - } - } in intnumleft=k-InL; -Root->lchild=create (postl,postl+numleft-1, inl,k-1); toRoot->rchild=create (postl+numleft,postr-1, K +1, InR); + returnRoot; - } the * //perform a hierarchical traversal $ intnum=0;Panax Notoginseng voidBFS (Node *root) - { thequeue<node* >Q; + Q.push (root); A while(!q.empty ()) the { +Node *now=Q.front (); - Q.pop (); $printf"%d",now->data); $num++; - if(num<N) -printf" "); the if(now->lchild!=NULL) -Q.push (now->lchild);Wuyi if(Now->rchild!=null)//because it takes a long time to add a punctuation mark here. theQ.push (now->rchild); - } Wu } - About intMainintargcChar*argv[]) $ { - -scanf"%d",&n); - for(intI=0; i<n;i++) Ascanf"%d",&post[i]); + for(intI=0; i<n;i++) thescanf"%d",&inch[i]); -node* Root=create (0, N-1,0, N-1); $ BFS (root); the return 0; the}View Code
PAT1020. Tree traversals