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, print on one line the level order traversal sequence of the CORRESP Onding 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.
#include <stdio.h> #include <stdlib.h> #include <queue>using namespace std;typedef struct node{int Id struct Node *left,*right; }node; Node * creat (int * post,int ps,int pe,int * in,int is,int IE); void BFS (Node * root); int N;int main () {int i; scanf ("%d", &n); int *post=new Int[n]; int *in=new Int[n]; for (i=0;i<n;i++) {scanf ("%d", post+i); } for (i=0;i<n;i++) {scanf ("%d", in+i); } Node *root=creat (post,0,n-1,in,0,n-1); BFS (root); printf ("\ n"); System ("pause"); return 0; }void BFS (Node * root) {Queue<node *>q; Q.push (root); Node *temp=new node; int count=0; while (!q.empty ()) {Temp=q.front (); Q.pop ();//Team printf ("%d", temp->id); count++; if (count<n) printf (""); if (temp->left) Q.push (temp->left); if (temp->right) Q.push (temp->right); }}node * creat (int * post,int ps,int pe,int * in,int is,int IE) {if (PS>PE) return NULL; Node * root=new node; root->id=post[pe]; int i; for (i=is;i<=ie;i++) if (in[i]==root->id) break; int num=i-is; Root->left=creat (post,ps,ps+num-1,in,is,i-1); Root->right=creat (Post,ps+num,pe-1,in,i+1,ie); return root; }
1020. Tree Traversals