1. 程式人生 > >PAT-A1020:Tree Traversal(二叉樹的重建及其中序、後序遍歷)

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;
}