二叉树遍历

二叉树遍历习题

题意:

给出一个二叉树的后序遍历序列和中序遍历序列,求这颗二叉树的层序遍历序列。

输入

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出

4 1 6 3 5 7 2
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>



using namespace std;


const int maxn=50;


typedef struct node{

    int data;
    node* lchild;
    node* rchild;

}Node;


int pre[maxn],in[maxn],post[maxn];  //先序,中序,后序 


int n;      //结点个数 


//create 函数返回构建出的二叉树的根结点地址

Node* create( int postL,int postR,int inL,int  inR ) 
{
    if(postL > postR)
    {
        return NULL;    //后序序列长度小于等于0时,直接返回 

    }


    Node* root = new Node;

    root->data = post[postR];   //新结点的数据域为根结点的值 

    int k;

    for(k=inL;k<=inR;k++)
    {
        if(in[k] == post[postR] )   //根据先序序列中根结点的值,在中序序列中找出根结点的位置 
        {
            break;
        }
    }

    int num_left=k-inL;     //左子树的结点个数

    //分治递归创建左子树和右子树


    root->lchild = create(postL,postL+num_left-1,inL,k-1);

    root->rchild = create(postL+num_left,postR-1,k+1,inR);

    return root; 



}


//已经输出的结点的个数 

int num=0;


void BFS(Node* root)
{

    queue<Node*> queue;

    queue.push(root);

    while(!queue.empty())
    {
        Node* now=queue.front();

        queue.pop();

        printf("%d",now->data);

        num++;

        if(num<n)
        {
            printf(" ");
        }


        if(now->lchild!=NULL)
        {
            queue.push(now->lchild);


        }

        if(now->rchild!=NULL)
        {
            queue.push(now->rchild);

        }


    }







}





int main()
{

    scanf("%d",&n);

    for(int i=0;i<n;i++)
    {
        scanf("%d",&post[i]);


    }

    for(int i=0;i<n;i++)
    {
        scanf("%d",&in[i]);

    }

    Node* root= create(0,n-1,0,n-1);

    BFS(root);



    return 0;
}


















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值