SDUWH 数据结构 树的遍历

树的遍历 (15分)

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:

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

输出样例:

4 1 6 3 5 7 2

题解: 

又双叒叕是根据中+前/后序建树==

也可以不用建树,递归过程把各层根节点打上顺序标记也可。

#include <bits/stdc++.h>
using namespace std;

const int maxn = 100;
bool flag;
int pre[maxn], in[maxn];
unordered_map<int, int> pos;
struct node
{
    int v;
    node *ls, *rs;
    node(int v)
    {
        this->v = v;
        ls = rs = nullptr;
    }
};

inline const int read()
{
    int x = 0, f = 1; char ch = getchar();
    while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + ch - '0'; ch = getchar(); }
    return x * f;
}

node* build(int pl, int pr, int il, int ir)
{
    if (pl > pr) return nullptr;
    node* now = new node(pre[pr]);
    int pos_in = pos[pre[pr]];
    int nl = pos_in - il;
    now->ls = build(pl, pl + nl - 1, il, pos_in - 1);
    now->rs = build(pl + nl, pr - 1, pos_in + 1, ir);
    return now;
}

void bfs(node* root)
{
    queue<node> q;
    q.push(*root);
    while (!q.empty())
    {
        node now = q.front();
        q.pop();
        printf("%s%d", flag ? " " : "", now.v);
        flag = true;
        if (now.ls) q.push(*(now.ls));
        if (now.rs) q.push(*(now.rs));
    }
}

int main()
{
    int n = read();
    for (int i = 1; i <= n; i++) pre[i] = read();
    for (int i = 1; i <= n; i++)
    {
        in[i] = read();
        pos[in[i]] = i;
    }
    node* root = build(1, n, 1, n);
    bfs(root);
    return 0;
}
发布了367 篇原创文章 · 获赞 148 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_35850147/article/details/103572723