K12137 二叉树中的秘密

K12137 二叉树中的秘密

今天我们再讲一题,二叉树中的秘密,先看题目和样例吧。

 

根据样例来看,飞神的遍历路线为1->2->1->3->4->3->5。 

 那么来看一下代码吧:

#include<bits/stdc++.h>
using namespace std;
int n,x,ans,ok,cnt[1000010];
struct Node{
	int l,r;
}t[100010];
int count(int r){
	if(r==0){
		return 0;
	}
	cnt[r]=count (t[r].l)+count(t[r].r)+1;
	return cnt[r];
}
void dfs(int r){
	if(ok||r==0){
		return ;
	}
	ans++;
	if(r==x){
		ok=1;
	}
	if(cnt[t[r].l]<=cnt[t[r].r]){
		dfs(t[r].l);
		dfs(t[r].r);
	}
	else{
		dfs(t[r].r);
		dfs(t[r].l);
	}
}
int main(){
	while(cin>>n>>x){
		ans=ok=0;
		memset(t,0,sizeof(t));
		for(int	i=1;i<=n;i++){
			int k,c[3]={0};
			cin>>k;
			for(int j=1;j<=k;j++){
				cin>>c[j];
			}
			if(c[1]&&c[2]&&c[1]>c[2]){
				swap(c[1],c[2]);
			}
			t[i].l=c[1];
			t[i].r=c[2];
		}
		count(1);
		dfs(1);
		cout<<ans<<endl;
	}
	
	return 0;
}

如有错误请及时指出,谢谢观看,拜拜~

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值