根据后序与中序遍历建树层序遍历输出

在我心里只要是二叉树就一定与递归有千丝万缕的关系,因此先递归建立左子树,再递归右子树,

像递归这种东西,一定要站在一个高度去看他,如果想的太复杂了会越陷越深,所以写代码是只要

给他一个宏观上的指令,就可以了。层序遍历吧,代码很简单,看一遍应该就理解了。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <cstdlib>

using namespace std;

int mid[100],post[100],pre[100];
int n;
struct node
{
    int c;
    node *lchild,*rchild;
};

//根据后序遍历与中序遍历递归建树
node *postMidCreatTree(int len, int *mid, int *post)
{
    int i;
    if(len<=0)
        return NULL;
    node *p = (node *)malloc(sizeof(node));
    p->lchild = p-> rchild = NULL;
    p->c = post[len-1];
    for(i=0; i<n; ++i)
        if(mid[i] == post[len-1])
            break;
    int l=i;
    p->lchild = postMidCreatTree(l,mid,post);
    p->rchild = postMidCreatTree(len-l-1,mid+l+1,post+l);
    return p;
}

//层序遍历
int levelTraverseTree(node *head)
{
    queue<node *>q;
    q.push(head);
    int i=0;

    while(!q.empty())
    {
        node *t;
        t = q.front();
        q.pop();
        pre[i++] = t->c;
        if(t->lchild)
        q.push(t->lchild);
        if(t->rchild)
        q.push(t->rchild);
    }

    return i;
}

int main()
{
    cin >> n;

    for(int i=0; i<n; ++i)
        cin >> post[i];
    for(int i=0; i<n; ++i)
        cin >> mid[i];

    node *head = (node *)malloc(sizeof(node));
    head->lchild = head->rchild = NULL;
    head = postMidCreatTree(n,mid,post);

    int len = levelTraverseTree(head);

    for(int i=0; i<len-1; ++i)
        cout << pre[i] << " ";
    cout << pre[len-1] << endl;
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值