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

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

#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;
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页