LeetCode 题解工作台
最深叶节点的最近公共祖先
给你一个有根节点 root 的二叉树,返回它 最深的叶节点的最近公共祖先 。 回想一下: 叶节点 是二叉树中没有子节点的节点 树的根节点的 深度 为 0 ,如果某一节点的深度为 d ,那它的子节点的深度就是 d+1 如果我们假定 A 是一组节点 S 的 最近公共祖先 , S 中的每个节点都在以 A …
5
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
我们设计一个函数 ,它将返回一个二元组 $(l, d)$,其中 是节点 的最深公共祖先,而 是节点 的深度。函数 的执行逻辑如下: - 如果 为空,则返回二元组 $(None, 0)$;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一个有根节点 root 的二叉树,返回它 最深的叶节点的最近公共祖先 。
回想一下:
- 叶节点 是二叉树中没有子节点的节点
- 树的根节点的 深度 为
0,如果某一节点的深度为d,那它的子节点的深度就是d+1 - 如果我们假定
A是一组节点S的 最近公共祖先,S中的每个节点都在以A为根节点的子树中,且A的深度达到此条件下可能的最大值。
示例 1:
输入:root = [3,5,1,6,2,0,8,null,null,7,4] 输出:[2,7,4] 解释:我们返回值为 2 的节点,在图中用黄色标记。 在图中用蓝色标记的是树的最深的节点。 注意,节点 6、0 和 8 也是叶节点,但是它们的深度是 2 ,而节点 7 和 4 的深度是 3 。
示例 2:
输入:root = [1] 输出:[1] 解释:根节点是树中最深的节点,它是它本身的最近公共祖先。
示例 3:
输入:root = [0,1,3,null,2] 输出:[2] 解释:树中最深的叶节点是 2 ,最近公共祖先是它自己。
提示:
- 树中的节点数将在
[1, 1000]的范围内。 0 <= Node.val <= 1000- 每个节点的值都是 独一无二 的。
注意:本题与力扣 865 重复:https://leetcode.cn/problems/smallest-subtree-with-all-the-deepest-nodes/
解题思路
方法一:DFS
我们设计一个函数 ,它将返回一个二元组 ,其中 是节点 的最深公共祖先,而 是节点 的深度。函数 的执行逻辑如下:
- 如果 为空,则返回二元组 ;
- 否则,我们递归调用 和 ,得到二元组 和 。如果 ,则 的最深公共祖先节点为 ,深度为 ;如果 ,则 的最深公共祖先节点为 ,深度为 ;如果 ,则 的最深公共祖先节点为 ,深度为 。
我们在主函数中调用 ,并返回其返回值的第一个元素,即可得到最深公共祖先节点。
时间复杂度 ,空间复杂度 。其中 是二叉树的节点数。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(root):
if root is None:
return None, 0
l, d1 = dfs(root.left)
r, d2 = dfs(root.right)
if d1 > d2:
return l, d1 + 1
if d1 < d2:
return r, d2 + 1
return root, d1 + 1
return dfs(root)[0]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates understanding of binary tree traversal techniques.
- question_mark
The candidate uses an optimal approach, focusing on DFS and state tracking.
- question_mark
The candidate explains how to compare depths and find the LCA efficiently.
常见陷阱
外企场景- error
Failing to correctly identify the deepest leaves before determining the LCA.
- error
Misunderstanding that the LCA must be common to the deepest nodes only.
- error
Overcomplicating the solution with unnecessary space or traversal steps.
进阶变体
外企场景- arrow_right_alt
Handling different tree structures, such as skewed trees or trees with only one node.
- arrow_right_alt
Optimizing for larger input sizes with stricter time/space constraints.
- arrow_right_alt
Adapting the solution to find the LCA for multiple nodes at varying depths.