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 (≤), 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

#include<stdio.h>
#include<queue>
using namespace std;
int num;
int postorder[50];
int inorder[50];
struct Tree
{
    Tree * leftchild;
    Tree * rightchild;
    int date;
};
queue<int> out;
Tree * findtree(int postL,int postR,int inL,int inR)
{
    if(postL>postR)   //postl=postr说明还有一个单个的 
    {
        return NULL;
    }
    Tree *root=new Tree;
    root->date=postorder[postR];
    int k;
    for(k=inL;k<inR;k++)
    {
        if(inorder[k]==postorder[postR])
        {
            break;
        }
    }
    int numLeft=k-inL;
    root->leftchild=findtree(postL,postL+numLeft-1,inL,k-1);
    root->rightchild=findtree(postL+numLeft,postR-1,k+1,inR);    //postr位为根 
    return root;
}

int n=0; 
void bfs(Tree* root)
{
    queue<Tree*> q;
    q.push(root);
    while(!q.empty())
    {
        Tree * now=q.front();
        q.pop();
        if(n!=num-1)
        {
        printf("%d ",now->date);
        n++;
        }
        else
        {
            printf("%d",now->date);
        }
        if(now->leftchild!=NULL)
        {
            q.push(now->leftchild);
                
        }
        if(now->rightchild!=NULL)
        {
            q.push(now->rightchild);
        }
    }

    
    
}
int main()
{

    scanf("%d",&num);
    for(int i=0;i<num;i++)
    {
        scanf("%d",&postorder[i]);
    }
    for(int i=0;i<num;i++)
    {
        scanf("%d",&inorder[i]);
    }
    Tree * root=findtree(0,num-1,0,num-1);
    bfs(root);
}

根据先序中序建树,bfs用queue实现即可