#include<bits/stdc++.h>
using namespace std;
#define in Read()
int in{
int i=0,f=1;char ch=0;
while(!isdigit(ch)&&ch!='-') ch=getchar();
if(ch=='-') ch=getchar(),f=-1;
while(isdigit(ch)) i=(i<<1)+(i<<3)+ch-48,ch=getchar();
return i*f;
}
const int N=1e5+5;
int root,sz;
struct node{
int lch,rch,val,dep;
}tre[N];
int new_root(int x,int y){
tre[++sz].val=x;
tre[sz].dep=y+1;
return sz;
}
void find(int rt,int x){
if(x<tre[rt].val){
if(!tre[rt].lch) tre[rt].lch=new_root(x,tre[rt].dep);
else find(tre[rt].lch,x);
}else{
if(!tre[rt].rch) tre[rt].rch=new_root(x,tre[rt].dep);
else find(tre[rt].rch,x);
}
return;
}
void postorder(int rt){
if(tre[rt].lch) postorder(tre[rt].lch);
if(tre[rt].rch) postorder(tre[rt].rch);
printf("%d\n",tre[rt].val);
return;
}
int main(){
int n=in;
for(int i=1;i<=n;++i){
int x=in;
if(!root) root=new_root(x,0);
else find(root,x);
}
int ans=0;
for(int i=1;i<=sz;++i) ans=max(ans,tre[i].dep);
printf("deep=%d\n",ans);
postorder(root);
return 0;
}
[BST][后序遍历] HZ吐泡泡
最新推荐文章于 2021-03-28 16:28:09 发布