[BST][后序遍历] HZ吐泡泡

Portkey

#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;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值