【题目描述】
给定一个二叉树,请编程计算它叶子节点的最小深度,假设根节点的深度为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;
}