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
#include#include #include #define MAX 35 using namespace std; typedef struct Node { int data; struct Node *left; struct Node *right; }Node; Node* ReBuild(int *Porder,int *Inorder,int len) { Node *root=(Node *)malloc(sizeof(Node)); if(!root) { printf("No enough memory!\n"); exit(-1); } if(len<=0) return NULL; root->left=NULL; root->right=NULL; root->data=Porder[len-1]; int i=0; for(i=0;i left=ReBuild(Porder,Inorder,i); root->right=ReBuild(Porder+i,Inorder+i+1,len-i-1); return root; } void LevelOrder(Node *root) { int first=1; queue q; if(root!=NULL) q.push(root); while(!q.empty()) { Node *temp; temp=q.front(); if(temp->left!=NULL) q.push(temp->left); if(temp->right!=NULL) q.push(temp->right); if(first) { printf("%d",temp->data); first=0; } else printf(" %d",temp->data); q.pop(); } printf("\n"); } int main(int argc,char *argv[]) { int n; int i,j; int Porder[MAX],Inorder[MAX]; scanf("%d",&n); for(i=0;i
重構二叉樹是很經典的一個題目。