PAT 甲 1020 Tree Traversals

2022.1.23 练习 PAT甲 1020 Tree Traversals (原题链接)

已知一个非空二叉树的中序遍历和后序遍历,求输出层序遍历。

题解如下:

#include <bits/stdc++.h>
using namespace std;
const int MAX_SIZE=30;
int post[MAX_SIZE];//后序
int in[MAX_SIZE];//中序
int n;


struct node
{
    int data;
    node* lchild;
    node* rchild;
};

node* create(int posl,int posr,int inl,int inr)
{
    if(posl>posr)
        return NULL;
    node* root=new node;
    root->data=post[posr];
    int k;
    for(k=inl;k<=inr;k++)
    {
        if(in[k]==post[posr])
            break;
    }
    int numleft=k-inl;
    root->lchild=create(posl,posl+numleft-1,inl,k-1);
    root->rchild=create(posl+numleft,posr-1,k+1,inr);
    return root;
}

void level(node* root)
{
    int num=0;
    queue<node*> q;
    q.push(root);
    while(!q.empty())
    {
        node* now=q.front();
        q.pop();
        cout<<now->data;
        num++;
        if(num<n)
            cout<<" ";
        if(now->lchild!=NULL)
            q.push(now->lchild);
        if(now->rchild!=NULL)
            q.push(now->rchild);
    }
}
int main()
{
    std::ios::sync_with_stdio(false);
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>post[i];
    for(int i=1;i<=n;i++)
        cin>>in[i];
    node* root=create(1,n,1,n);
    level(root);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值