L2-006 树的遍历 (25分)团体设计天梯赛

16 篇文章 0 订阅

知道一棵二叉树的先序或后序再知道中序,即可将该二叉树构造出来

#include <bits/stdc++.h>
using namespace std;
const int N = 35;
int postArr[N], inArr[N];
typedef struct Node
{
    int v;
    Node *lchild;
    Node *rchild;
} Node, *Tree;

Tree create(int postL, int postR, int inL, int inR)
{
    if (postL > postR)
        return NULL;
    Tree root = (Tree)malloc(sizeof(Node));
    int x = postArr[postR];
    root->v = x;
    int idx = -1;
    for (int i = inL; i <= inR; i++)
    {
        if (inArr[i] == x)
        {
            idx = i;
        }
    }
    int cnt = idx - inL;
    root->lchild = create(postL, postL + cnt - 1, inL, idx - 1);
    root->rchild = create(postL + cnt, postR - 1, idx + 1, inR);
    return root;
}
void layerOrder(Tree tree)
{
    queue<Tree> Q;
    Q.push(tree);
    bool flag = false;
    while (!Q.empty())
    {
        Tree T = Q.front();
        Q.pop();
        if (flag)
        {
            printf(" ");
        }
        printf("%d", T->v);
        if (T->lchild != NULL)
            Q.push(T->lchild);
        if (T->rchild != NULL)
            Q.push(T->rchild);
        flag = true;
    }
}
int main(void)
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &postArr[i]);
    }
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &inArr[i]);
    }
    Tree tree = create(0, n - 1, 0, n - 1);
    layerOrder(tree);
    printf("\n");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值