【题解搬运】PAT_A1020 树的遍历

本文介绍了一种根据给定的后序遍历和中序遍历序列来构造二叉树,并输出该树的层序遍历序列的方法。通过递归思想实现,详细解释了如何确定根节点及左右子树,最终完成树的构建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从我原来的博客上搬运。原先blog作废。

题目

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

题解

这题搞了我一个小时!!!好气啊,我们好好梳理一下这条题目。其实摸鱼了半个小时

给定一棵二叉树的后根遍历和中根遍历,求其前根遍历。
如何做呢?这里一定要有递归的思想。我们设定一个int makeTree(int l,int r);函数返回的是这棵树的根在动态数组(vector)的位置感觉指针更好写;和r是它元素的范围。那么显然main函数调用的是makeTree(0,n-1)。后面就很好写了!(一点也不
定义一个cur变量,它指的是下一次调用makeTree函数时的根节点,rootIdx则为目前树的根节点。那么后根遍历都知道是右→左→根,那么我们根据后根遍历构建树,根据中根遍历找左右子树,找到左右子树的边界以后递归调用makeTree函数即可。特别地,如果l>r,说明此树不存在;如果l==r,说明此节点是叶子节点,一一特判即可。这条题目以前我就不会写,今天放在这里,警戒自己学习一个。

特别地,以前还看过这样类似的题型:已知前根遍历和后根遍历,求有几种可能的(二叉)树。我们之后讨论一下。

代码

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

#define f1(x,y) for(int x=1;x<=y;++x)
#define f0(x,y) for(int x=0;x!=y;++x)
#define bf1(x,y,z) for(int x=y;x>=z;--x)
#define bf0(x,y,z) for(int x=y;x!=z;--x)
typedef long long ll;
typedef unsigned long long ull;
int n;
vector<int> inOrd,posOrd;
int cur;

struct Tree
{
    int id;
    int lp,rp;
    Tree(int _i):id(_i),lp(-1),rp(-1) {}
};
vector<Tree> t;
int makeTree(int l,int r)
{
    if(l>r) return -1;
    int nowIdx=cur--;
    int rootIdx=0;
    for(int i=0;i!=inOrd.size();++i)
        if(inOrd[i]==posOrd[nowIdx])
        {
            rootIdx=i;break;
        }
    t.push_back(Tree(inOrd[rootIdx]));
    int np=t.size()-1;
    if(l==r)
        t[np].rp=t[np].lp=-1;
    else
    {
        int tmp=makeTree(rootIdx+1,r);
        t[np].rp=tmp;
        tmp=makeTree(l,rootIdx-1);
        t[np].lp=tmp;
    }
    return np;
}
int main()
{
    cin>>n;
    int x;
    f0(i,n)
    {
        cin>>x;
        posOrd.push_back(x);
    }
    f0(i,n)
    {
        cin>>x;
        inOrd.push_back(x);
    }
    cur=n-1;
    int root=makeTree(0,n-1);

    queue<int> q;
    q.push(root);
    while(!q.empty())
    {
        int tr=q.front(); q.pop();
        if(tr==root) printf("%d",t[tr].id);
        else printf(" %d",t[tr].id);
        if(t[tr].lp!=-1) q.push(t[tr].lp);
        if(t[tr].rp!=-1) q.push(t[tr].rp);
    }
    printf("\n");
/*    for(int i=0;i!=5;++i)
    {
        printf("%d: %d<-self->%d\n",t[i].id,((t[i].lp==-1)?-1:(t[t[i].lp].id)),((t[i].rp==-1)?-1:(t[t[i].rp].id)));
    }*/
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值