Binary Tree Traversals 中序和前序求后序遍历
二叉树的遍历,这个题不能用T[4*N]建树,因为最坏的情况树很深,数组会爆的,2^1000
s所以求后续遍历的话,就反着来 根节点—>右子树—>左子树,然后把结果用stack存起来倒叙输出就好了
// preorder sequence inorder sequence postorder sequence. #include<bits/stdc++.h> #define endl '\n' #define _for(i,a,b) for(int i=a;i<b;i++) using namespace std; const int N = 1055; typedef long long ll; int pre[N],in[N]; stack<int> Sta; void Build( int s1,int e1,int s2,int e2 ){//s1e1是前序的,s2e2是中序的 Sta.push( pre[s1] ); int cnt = 0; _for(i,s2,e2+1){ if( in[i] == pre[s1] ) break; cnt++; } if( s1+cnt+1<=e1 ) Build( s1+cnt+1,e1,s2+cnt+1,e2 ); if( s1+1<=s1+cnt ) Build( s1+1,s1+cnt,s2,s2+cnt-1 ); } int main(){ ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); int n; while(cin>>n){ _for(i,1,n+1) cin>>pre[i]; _for(i,1,n+1) cin>>in[i]; Build( 1,n,1,n ); cout<<Sta.top(); Sta.pop(); while( Sta.size() ){ cout<<' '<<Sta.top(); Sta.pop(); } cout<<endl; } return 0; }