1020. Tree Traversals (25)
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 7Sample Output:
4 1 6 3 5 7 2
这题也不难,由后序跟中序序列构建一颗树,然后以层次遍历的方法输出各节点数据,主要输出后要把树给销毁,不然会造成内存泄露。
代码
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef struct Node{ 5 int data; 6 struct Node *left,*right; 7 }Node; 8 int postOrder[30]; 9 int inOrder[30]; 10 Node* buildTree(int,int,int,int); 11 void printAndDestroyTree(Node *); 12 int main() 13 { 14 int N,i; 15 while(scanf("%d",&N) != EOF){ 16 for(i=0;i<N;++i){ 17 scanf("%d",&postOrder[i]); 18 } 19 for(i=0;i<N;++i){ 20 scanf("%d",&inOrder[i]); 21 } 22 Node *tree = buildTree(0,N-1,0,N-1); 23 printAndDestroyTree(tree); 24 } 25 return 0; 26 } 27 28 Node* buildTree(int postStart,int postEnd,int inStart,int inEnd) 29 { 30 if(postStart == postEnd){ 31 Node *p = (Node *)malloc(sizeof(Node)); 32 p->data = postOrder[postStart]; 33 p->left = p->right = NULL; 34 return p; 35 } 36 else{ 37 Node *p = (Node *)malloc(sizeof(Node)); 38 p->data = postOrder[postEnd]; 39 p->left = p->right = NULL; 40 int i = inStart; 41 while(i<=inEnd && postOrder[postEnd] != inOrder[i++]); 42 if(i > inStart+1) 43 p->left = buildTree(postStart,postStart+i-inStart-2,inStart,i-2); 44 if(i <= inEnd) 45 p->right = buildTree(postStart+i-inStart-1,postEnd-1,i,inEnd); 46 return p; 47 } 48 } 49 50 void printAndDestroyTree(Node *p) 51 { 52 if(!p) 53 return; 54 Node *nodeArray[30]; 55 int top=0,base=0; 56 Node *q; 57 nodeArray[top++] = p; 58 while(top>base){ 59 q = nodeArray[base++]; 60 if(base == 1) 61 printf("%d",q->data); 62 else 63 printf(" %d",q->data); 64 if(q->left) 65 nodeArray[top++] = q->left; 66 if(q->right) 67 nodeArray[top++] = q->right; 68 free(q); 69 } 70 printf(" "); 71 }