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<cstdio>
#include<cstdlib>
#include<queue>
#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<len;i++)
if(Porder[len-1]==Inorder[i])
break;
root->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<Node *> 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<n;i++)
scanf("%d",&Porder[i]);
for(j=0;j<n;j++)
scanf("%d",&Inorder[j]);
Node *tree=ReBuild(Porder,Inorder,n);
LevelOrder(tree);
return 0;
}
Pat(Advanced Level)Practice--1020(Tree Traversals),布布扣,bubuko.com
Pat(Advanced Level)Practice--1020(Tree Traversals)
原文:http://blog.csdn.net/cstopcoder/article/details/23706459