牛客网在线编程(二):数的高度-python

版权声明:本文为博主原创文章,未经博主允许不得转载。转载请注明作者和出处:https://blog.csdn.net/weixin_41481113 https://blog.csdn.net/weixin_41481113/article/details/83588736

题目描述

现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度

输入描述:

输入的第一行表示节点的个数n(1 ≤ n ≤ 1000,节点的编号为0到n-1)组成,
下面是n-1行,每行有两个整数,第一个数表示父节点的编号,第二个数表示子节点的编号

输出描述:

输出树的高度,为一个整数

示例1

输入

5
0 1
0 2
1 3
1 4

输出

3

代码实现

import sys

lines = sys.stdin.readlines()

N=int(lines[0])
node=[]
height=[0]*N
height[0]=1
child_num=[0]*N
for i in range(1,N):
    node.append(tuple(lines[i].split()))
for i in range(N-1):
    if child_num[int(node[i][0])]<2:
        height[i+1]=height[int(node[i][0])]+1
        child_num[int(node[i][0])]+=1
print(max(height))

猜你喜欢

转载自blog.csdn.net/weixin_41481113/article/details/83588736