PAT 甲 1020 Tree Traversals

PAT 甲 1020 Tree Traversals,第1张

PAT 甲 1020 Tree Traversals

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

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

题解如下:

#include 
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 q;
    q.push(root);
    while(!q.empty())
    {
        node* now=q.front();
        q.pop();
        cout<data;
        num++;
        if(numlchild!=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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5713502.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存