标签:
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
思想:中序 加后序 然后层次序列遍历 很简单的题。 之所以耗费了好长时间是因为标点符号,if后面加了标点符号。
1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 #include <algorithm> 5 using namespace std; 6 const int maxn=50; 7 struct node 8 { 9 int data; 10 node *lchild; 11 node *rchild; 12 }; 13 int in[maxn],post[maxn]; 14 int n; 15 node * create(int postL,int postR,int inL,int inR) 16 { 17 if(postL>postR) 18 return NULL; 19 node *root=new node; 20 root->data=post[postR]; 21 int k; 22 for(k=inL;k<=inR;k++) 23 { 24 if(in[k]==post[postR]) 25 { 26 break; 27 } 28 } 29 int numLeft=k-inL; 30 root->lchild=create(postL,postL+numLeft-1,inL,k-1); 31 root->rchild=create(postL+numLeft,postR-1,k+1,inR); 32 return root; 33 } 34 35 //进行层次遍历 36 int num=0; 37 void BFS(node *root) 38 { 39 queue<node* >q; 40 q.push(root); 41 while(!q.empty()) 42 { 43 node *now=q.front(); 44 q.pop(); 45 printf("%d",now->data); 46 num++; 47 if(num<n) 48 printf(" "); 49 if(now->lchild!=NULL) 50 q.push(now->lchild); 51 if(now->rchild!=NULL) //因为此处加了一个标点符号导致花费好长时间。 52 q.push(now->rchild); 53 } 54 } 55 56 int main(int argc, char *argv[]) 57 { 58 59 scanf("%d",&n); 60 for(int i=0;i<n;i++) 61 scanf("%d",&post[i]); 62 for(int i=0;i<n;i++) 63 scanf("%d",&in[i]); 64 node* root=create(0,n-1,0,n-1); 65 BFS(root); 66 return 0; 67 }
标签:
原文地址:http://www.cnblogs.com/GoFly/p/4299850.html