本文共 1292 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要建立一棵二叉树,并计算其深度。二叉树的深度是指从根节点到叶子节点时,最多经过了几层。我们可以使用广度优先搜索(BFS)来高效地计算每个节点的深度,并找出最大深度。
import sysfrom collections import dequedef compute_tree_depth(): n = int(sys.stdin.readline()) tree = [[0, 0] for _ in range(n + 1)] # 1-based indexing for i in range(1, n + 1): l, r = map(int, sys.stdin.readline().split()) tree[i] = (l, r) max_depth = 1 # root node's depth queue = deque() queue.append(1) while queue: current = queue.popleft() l, r = tree[current] current_depth = max_depth if l != 0: l_depth = current_depth + 1 if l_depth > max_depth: max_depth = l_depth queue.append(l) if r != 0: r_depth = current_depth + 1 if r_depth > max_depth: max_depth = r_depth queue.append(r) print(max_depth)if __name__ == "__main__": compute_tree_depth()
tree来存储每个节点的左和右子节点。通过这种方法,我们可以高效地计算出二叉树的深度,适用于大规模节点数的情况。
转载地址:http://cgoo.baihongyu.com/