PAT L2-006. 树的遍历

本文介绍了一种通过给定的二叉树后序和中序遍历序列来求解层次遍历的方法。利用递归的方式从后序遍历序列中确定根节点,并在中序遍历中定位该根节点以划分左右子树,进而实现二叉树的重构。最后通过广度优先搜索(BFS)完成层次遍历的输出。

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

题目链接:https://www.patest.cn/contests/gplt/L2-006

题意:由二叉树的后序和中序求层次遍历。

二叉树的还原:用先序或后序的顺序递归中序来建树。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>

using namespace std;

#define FOR(i,k,n) for(int i=k;i<n;i++)
#define FORR(i,k,n) for(int i=k;i<=n;i++)
#define scan(a) scanf("%d",&a)
#define scann(a,b) scanf("%d%d",&a,&b)
#define scannn(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define mst(a,n)  memset(a,n,sizeof(a))
#define ll long long
#define N 105
#define mod 1000000007
#define INF 0x3f3f3f3f

const double eps=1e-8;
const double pi=acos(-1.0);
struct node
{
    int l,r;
    node()
    {
        l=r=0;
    }
}tree[N];
queue<int> q;
int postorder[N],inorder[N];
int post;
int n;
void build(int root,int l,int r)
{
    int i=r;
    for(;i>=l;i--)
    {
        if(inorder[i]==postorder[post]) break;
    }
    if(i<r)
    {
        tree[root].r=postorder[--post];
        build(tree[root].r,i+1,r);
    }
    if(i>l)
    {
        tree[root].l=postorder[--post];
        build(tree[root].l,l,i-1);
    }
}

void Bfs(int root)
{
    while(!q.empty()) q.pop();
    int cnt=0;
    cnt++;
    printf("%d%c",root,cnt==n?'\n':' ');
    q.push(root);
    while(!q.empty())
    {
        int cur=q.front();
        q.pop();
        if(tree[cur].l) cnt++,printf("%d%c",tree[cur].l,cnt==n?'\n':' '),q.push(tree[cur].l);
        if(tree[cur].r) cnt++,printf("%d%c",tree[cur].r,cnt==n?'\n':' '),q.push(tree[cur].r);
    }
}

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);


    while(~scan(n))
    {
        mst(tree,0);
        post=n-1;
        FOR(i,0,n) scan(postorder[i]);
        FOR(i,0,n) scan(inorder[i]);
        int root=postorder[n-1];
        build(root,0,n-1);
        Bfs(root);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值