1119 Pre- and Post-order Traversals

本文详细介绍了二叉树的前序和后序遍历算法,包括递归和非递归实现方式,并通过实例进行解析,帮助读者深入理解这两种遍历方法。
摘要由CSDN通过智能技术生成
#include<bits/stdc++.h>
using namespace std;
#define mst(x,y) memset(x,y,sizeof(x))
#define rep(x,y,z) for(int x=(y);(x)<(z);x++)
const int maxn=100+10;
int n,a[maxn],b[maxn];
int nxt[maxn][2],flag=1,tmp=0;
int cnt[1000005];
void build(int l1,int r1,int l2,int r2,int pre){  
    if(l1>r1||l2>r2) return ;
    ///cout<<l1<<" "<<r1<<" "<<l2<<" "<<r2<<" "<<tmp<<endl;
    if(a[l1]==b[r2]){
        if(tmp){
            flag=0;
         	///cout<<l1<<" "<<r1<<" "<<l2<<" "<<r2<<endl;   
        }
        else tmp++;
        nxt[pre][cnt[pre]++]=a[l1];
        build(l1+1,r1,l2,r2-1,a[l1]);
    }else{
        tmp=0;
        int idx=l2;while(b[idx]!=a[l1]) idx++;
        int mov=idx-l2+1;
        build(l1,l1+mov-1,l2,idx,pre);
        build(l1+mov,r1,idx+1,r2,pre);
    }
    tmp=0;
    return ;
}
vector<int> ans;
void dfs(int u){
    if(u==-1) return ;
    dfs(nxt[u][0]);
    ans.push_back(u);
    dfs(nxt[u][1]);
}
int main(){
    mst(nxt,-1);
    ios::sync_with_stdio(false);
    cin>>n;
    rep(i,1,n+1) cin>>a[i];
    rep(i,1,n+1) cin>>b[i];
    build(1,n,1,n,0);
    if(flag) cout<<"Yes\n";
    else cout<<"No\n";
    dfs(a[1]);
    rep(i,0,ans.size()){
        cout<<ans[i];
        if(i!=ans.size()-1) cout<<" ";
        else cout<<"\n";
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值