用 Python 编写程序来查找 n 叉树的直径
pythonserver side programmingprogramming更新于 2025/5/3 5:32:17
假设,我们给定一棵 n 叉树,并要求确定树的直径。树的直径是树的任意两个叶节点之间的最长路径。我们必须找出并返回代表树直径的整数值。
因此,如果输入如下

则输出为 3。
此 n 元树的直径由边 27->14、14->42 和 42->56 或 42->65 组成(在图中用红线标记)。路径长度为 3。
为了解决这个问题,我们将遵循以下步骤 −
ans := 1
定义一个函数depth()。这将使根节点生根
如果根节点不为空,则
返回 0
children := 一个包含值 0, 0 的新列表
temp_children := 一个新列表
对于根节点的 children 中的每个子节点,执行
在 temp_children 的末尾插入depth(child)
如果 size of (temp_children) > 0,然后
children := temp_children
ans := 最大值 ans,sum(对列表 children 进行排序 [从 (children)- 2 的索引长度到末尾]) + 1
返回最大值 children + 1
depth(root)
return(ans -1)
示例 (Python)
让我们看看下面的实现以便更好地理解 −
class Node: def __init__(self, value, child = None) -> None: self.val = value self.children = [] if child != None: for value in child: self.children.append(value) ans = 1 def solve(root): def depth(root): global ans if not root: return 0 children = [0, 0] temp_children = [depth(child) for child in root.children] if len(temp_children) > 0: children = temp_children ans = max(ans, sum(sorted(children)[-2:]) + 1) return max(children) + 1 depth(root) return ans -1 node6 = Node(65) node5 = Node(56) node4 = Node(42, [node5, node6]) node3 = Node(32) node2 = Node(27) node1 = Node(14, [node2, node3, node4]) root = node1 print(solve(root))
输入
node6 = Node(65) node5 = Node(56) node4 = Node(42, [node5, node6]) node3 = Node(32) node2 = Node(27) node1 = Node(14, [node2, node3, node4]) root = node1
输出
3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

