PTA A 1020 Tree Traversals

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

#include<cstdio>
#define maxn 102
#include<algorithm>
#include<vector>
#include<cmath>
#include<iostream>
#include<queue>
using namespace std;
vector<int>postorder;
vector<int>inorder;
//利用后序序列和中序序列递归建树,递归边界是序列长度小于等于0,
//在递归程序中,输入序列左右两端点下标,先处理后序序列,得到序列对应树的根,然后处理中序序列,得到
//对应树的左子树右子树序列的左右端点下标,递归进行此过程,直到递归边界
struct node
{
    
    
    int data;
    node* lchild;
    node* rchild;
};
node* build(int postL,int postR,int inL,int inR )
{
    
    
    if(postL>postR){
    
    
        return NULL;
    }
    node *root=new node;
    root->data=postorder[postR];
    root->lchild=NULL;
    root->rchild=NULL;
    int index;
    for(index=inL;index<=inR;index++){
    
    
        if(inorder[index]==postorder[postR]){
    
    
            break;
        }
    }
    int length=index-inL;//左子树长度
    root->lchild=build(postL,postL+length-1,inL,index-1);//index-inL是前序序列左子树的长度
    root->rchild=build(postL+length,postR-1,index+1,inR);
    return root;
}
void Layerorder(node *root)
{
    
    
    if(root==NULL){
    
    
        return ;
    }
    queue<node*>q1;
    q1.push(root);
    node *temp;
    int flag=0;
    while(!q1.empty()){
    
    
        temp=q1.front();
        if(flag==0){
    
    
            printf("%d",temp->data);
            flag=1;
        }
        else{
    
    
            printf(" %d",temp->data);
        }
        q1.pop();
        if(temp->lchild!=NULL){
    
    
            q1.push(temp->lchild);
        }
        if(temp->rchild!=NULL){
    
    
            q1.push(temp->rchild);
        }
    }
}
int main()
{
    
    
    int length;
    scanf("%d",&length);
    int temp;
    for(int i=0;i<length;i++){
    
    
        scanf("%d",&temp);
        postorder.push_back(temp);
    }
    for(int i=0;i<length;i++){
    
    
        scanf("%d",&temp);
        inorder.push_back(temp);
    }
    node* root;
    root=build(0,postorder.size()-1,0,inorder.size()-1);
    Layerorder(root);
    return 0;
}


猜你喜欢

转载自blog.csdn.net/weixin_45890608/article/details/111329623