1138 Postorder Traversal (25 分) (前序 中序 后序输出

添加链接描述

#include<bits/stdc++.h>
using namespace std;
const int N=5e4+9;
int pre[N],in[N];
typedef struct  node
{
    int data;
    node *l,*r;
}bitnode,*bittree;
node *build(int prel,int prer,int inl,int inr){
    node *root;
    root=new node ();
    if(prer<prel)return NULL;
    int k=inl;
    while(in[k]!=pre[prel])k++;
    int len=k-inl;
    root->data=in[k];
    root->l=build(prel+1,prel+len,inl,inl+len-1);
    root->r=build(prel+len+1,prer,k+1,inr);
    return root;
}
int ok=0;
vector<int> ans;
void dfs(node *root){
    if(ok)return ;
    if(root==NULL)return;
    if(root->l!=NULL)dfs(root->l);
    if(root->r!=NULL)dfs(root->r);
    ans.push_back(root->data);
    ok=1;
}
int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>pre[i];
    }
    for(int i=1;i<=n;i++){
        cin>>in[i];
    }
    bittree root;
    root=NULL;
    root=build(1,n,1,n);
    dfs(root);
    cout<<ans[0]<<endl;

    return 0;
}
上一篇:25、如何计算车辆的出车次数?


下一篇:题223.2022寒假天梯赛训练-7-12 清点代码库 (25 分)