PAT L2-006 树的遍历

L2-006. 树的遍历

时间限制: 400 ms
内存限制: 65536 kB
代码长度限制: 8000 B
判题程序: Standard
作者: 陈越

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

输入格式:

输入第一行给出一个正整数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

问题分析

由树的中序遍历和后序遍历来构建一颗二叉树,然后bfs遍历。
难点估计就在于怎么利用中序遍历和后序遍历来构建一颗二叉树了…..
要解决这道题,那就得先了解一下中序遍历和后序遍历的便利顺序了。

前序遍历:根节点->左子树->右子树
中序遍历:左子树->根节点->右子树
后序遍历:左子树->右子树->根节点

所以知道以上遍历顺序之后,我们就可以开始构建二叉树了,我们可以先找到后序遍历的最后一个元素,后序遍历的最后一个元素一定是这颗二叉树的根。

int root = post_order[r2];

又根据中序遍历的顺序,可以找到中序遍历中根节点所在位置,然后就可以得到左子树和右子树的节点个数。

    int p = l1;
    while(in_order[p]!=root) p++;
    int cnt = p-l1; //左子树节点个数

接下来继续根据后序遍历和中序遍历来递归构建二叉树即可。

    lch[root] = build(l1,p-1,l2,l2+cnt-1);
    rch[root] = build(p+1,r1,l2+cnt,r2-1);

ok,接下来上AC code(^_^)

#include <bits/stdc++.h>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 31;
int in_order[31],post_order[31],lch[N],rch[N];
int n;

int build(int l1,int r1,int l2,int r2)
{
    if(l1>r1)
    return 0;
    int root = post_order[r2];
    int p = l1;
    while(in_order[p]!=root)//在中序遍历中寻找根节点位置
    p++;
    int cnt = p-l1;//左子树节点个数
    lch[root] = build(l1,p-1,l2,l2+cnt-1);
    rch[root] = build(p+1,r1,l2+cnt,r2-1);
    return root;
}

void bfs()
{
    queue<int> q;
    std::vector<int> v;
    q.push(build(0,n-1,0,n-1));
    while(!q.empty())
    {
        int cur = q.front();
        q.pop();
        v.push_back(cur);
        if(lch[cur])
        q.push(lch[cur]);
        if(rch[cur])
        q.push(rch[cur]);
    }
    for(int i = 0; i < v.size(); ++i)
    printf("%d%c",v[i],i==v.size()-1?'\n':' ');
}

int main()
{
    // freopen("in.txt","r",stdin);
    cin>>n;
    for(int i = 0; i < n; ++i)
        cin>>post_order[i];
    for(int i = 0; i < n; ++i)
        cin>>in_order[i];
    bfs();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/eternally831143/article/details/79719367