用 Python 编写程序来查找树的最左最深节点
pythonserver side programmingprogramming更新于 2026/1/19 7:40:17
假设我们有一棵二叉树;我们必须找到最深节点的值。如果有多个最深节点,则返回最左边的最深节点。
因此,如果输入如下

则输出将为 4,因为 4 和 7 最深,但 4 最左边。
为了解决这个问题,我们将遵循以下步骤 −
队列 := 具有一个节点根的队列。
left_max := 根的值
而队列大小 > 0,执行
level_size := 队列大小
对于范围在 0 到 level_size 内的 i,执行
temp := 队列中的第一个元素并删除它
如果 i 与 0 相同,则
left_max := temp 的值
如果 temp 的左侧非零,则
将 temp 的左侧插入队列末尾
如果 temp 的右侧不为空,则
将 temp 的右侧插入队列末尾队列
返回 left_max
让我们看看下面的实现以便更好地理解 −
示例
class TreeNode: def __init__(self, value): self.val = value self.left = None self.right = None class Solution: def solve(self, root): queue = [root] left_max = root.val while len(queue) > 0: level_size = len(queue) for i in range(level_size): temp = queue.pop(0) if i == 0: left_max = temp.val if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) return left_max ob = Solution() root = TreeNode(13) root.left = TreeNode(12) root.right = TreeNode(14) root.right.left = TreeNode(16) root.right.right = TreeNode(22) root.right.left.left = TreeNode(4) root.right.left.right = TreeNode(7) print(ob.solve(root))
输入
root = TreeNode(13) root.left = TreeNode(12) root.right = TreeNode(14) root.right.left = TreeNode(16) root.right.right = TreeNode(22) root.right.left.left = TreeNode(4) root.right.left.right = TreeNode(7)
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

