PAT 甲 1086 Tree Traversals Again

2022.1.28 练习 PAT甲 1086 Tree Traversals Again (原题链接)

已知先序和中序遍历,求后序遍历

题解如下:

#include <bits/stdc++.h>
using namespace std;
int n;

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

stack<int> inorder;
vector<int> pre;
vector<int> in;
vector<int> post;

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

void postorder(node* root)
{
    if(root==NULL)
        return ;
    postorder(root->lchild);
    postorder(root->rchild);
    post.push_back(root->data);
}
int main()
{
    std::ios::sync_with_stdio(false);
    cin>>n;
    int m=2*n;
    while(m--)
    {
        string tmp;
        cin>>tmp;
        if(tmp=="Push")
        {
            int num;
            cin>>num;
            pre.push_back(num);
            inorder.push(num);

        }
        else if(tmp=="Pop")
        {
            int num=inorder.top();
            in.push_back(num);
            inorder.pop();
        }
    }
    node* root=create(0,n-1,0,n-1);
    postorder(root);
    for(vector<int>::iterator it=post.begin();it!=post.end();it++)
    {
        cout<<*it;
        if(it<post.end()-1)
            cout<<" ";
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值