PAT-A1020:Tree Traversal(二叉树的重建及其中序、后序遍历)

题目传送门:https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072

目录

题目解释:

解题思路:

ac代码:

题目解释:


给出一棵二叉树(binary tree)的后序(postorder)遍历和中序(inorder)遍历,要求重建这棵二叉树,并输出这棵二叉树的层序遍历序列。

 

解题思路:


《算法笔记》P297,重建后输出就行,调用create和bfs函数,使代码清晰一些,注意输出格式

 

ac代码:


#include <iostream>
#include <stdlib.h>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct node{
    int data;
    node* lchild;
    node* rchild;
};
int pre[50],in[50],post[50];//先序,中序,后序
int n;//全局变量
node* create(int postl,int postr,int inl,int inr)
{
    int k;
    if(postl>postr)
        return NULL;
    node* root=new node;
    root->data=post[postr];
    for(k=inl;k<=inr;k++)
        if(in[k]==post[postr])
            break;
    int numleft=k-inl;
    root->lchild=create(postl,postl+numleft-1,inl,k-1);//左子树
    root->rchild=create(postl+numleft,postr-1,k+1,inr);//右子树
    return root;

}
void bfs(node* root)
{
    int num=0;
    queue<node* > q;
    q.push(root);
    while(!q.empty())
    {
        node* now=q.front();
        q.pop();
        printf("%d",now->data);
        num++;
        if(num<n)
            printf(" ");
        if(now->lchild!=NULL) q.push(now->lchild);
        if(now->rchild!=NULL) q.push(now->rchild);
    }
}
int main()
{
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",&post[i]);
    for(int i=0;i<n;i++)
        scanf("%d",&in[i]);
    node* root=create(0,n-1,0,n-1);
    bfs(root);
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值