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

版权声明:转载请注明出处哦~ https://blog.csdn.net/Cassie_zkq/article/details/82915267

题目传送门: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;
}

猜你喜欢

转载自blog.csdn.net/Cassie_zkq/article/details/82915267