树的最小深度

【题目描述】

给定一个二叉树,请编程计算它叶子节点的最小深度,假设根节点的深度为1。

【输入】

输入第一行一个整数n,表示有n个结点; 接下来输入n行每行三个数字,分别表示结点编号(0~n-1,0为根节点),父节点编号(-1表示无),左右子树(0左1右-1为根)。1≤n≤1000000。

【输出】

输出一个整数。

【输入样例】

7 0 -1 -1 1 0 0 3 0 1 2 1 0 4 1 1 5 2 0 6 2 1

【输出样例】

2

#include <bits/stdc++.h>
using namespace std;

int n, self, parent, tp, head, ans;

struct Node
{
	int id;
	int parent;
	int left;
	int right;
	int depth;
};

queue <int> qu;
Node a[1000001];

int main()
{
	cin >> n;
	for(int i = 0; i < n; i++)
	{
		cin >> self >> parent >> tp;
		a[self].id = self;
		a[self].parent = parent;
		a[self].left = -1;
		a[self].right = -1;
		if(parent != -1)
		{
			if(tp == 0) a[parent].left = self;
			if(tp == 1) a[parent].right = self;
		}
	}
	qu.push(0);
	a[0].depth = 1;
	while(qu.empty() == false)
	{
		head = qu.front();
		if(a[head].left == -1 && a[head].left == -1)
		{
			ans = a[head].depth;
			break;
		}
		if(a[head].left != -1)
		{
			a[a[head].left].depth = a[head].depth + 1;
			qu.push(a[head].left);
		}
		if(a[head].right != -1)
		{
			a[a[head].right].depth = a[head].depth + 1;
			qu.push(a[head].right);
		}
		qu.pop();
	}
	cout << ans << endl;
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值