LeetCode 题解工作台
二叉搜索树的最近公共祖先
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 百度百科 中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大( 一个节点也可以是它自己的祖先 )。” 例如,给定如下二叉…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
我们从根节点开始遍历,如果当前节点的值小于 和 的值,说明 和 应该在当前节点的右子树,因此将当前节点移动到右子节点;如果当前节点的值大于 和 的值,说明 和 应该在当前节点的左子树,因此将当前节点移动到左子节点;否则说明当前节点就是 和 的最近公共祖先,返回当前节点即可。 时间复杂度 ,其中 是二叉搜索树的节点个数。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]

示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 输出: 6 解释: 节点2和节点8的最近公共祖先是6。
示例 2:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 输出: 2 解释: 节点2和节点4的最近公共祖先是2, 因为根据定义最近公共祖先节点可以为节点本身。
说明:
- 所有节点的值都是唯一的。
- p、q 为不同节点且均存在于给定的二叉搜索树中。
解题思路
方法一:迭代
我们从根节点开始遍历,如果当前节点的值小于 和 的值,说明 和 应该在当前节点的右子树,因此将当前节点移动到右子节点;如果当前节点的值大于 和 的值,说明 和 应该在当前节点的左子树,因此将当前节点移动到左子节点;否则说明当前节点就是 和 的最近公共祖先,返回当前节点即可。
时间复杂度 ,其中 是二叉搜索树的节点个数。空间复杂度 。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(
self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode'
) -> 'TreeNode':
while 1:
if root.val < min(p.val, q.val):
root = root.right
elif root.val > max(p.val, q.val):
root = root.left
else:
return root
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate correctly identifies the LCA concept and binary search tree traversal patterns.
- question_mark
Candidate efficiently explains the use of DFS and state tracking in LCA search.
- question_mark
Candidate discusses time and space complexities relevant to the tree's structure and traversal.
常见陷阱
外企场景- error
Confusing binary tree traversal with BFS, leading to inefficient solutions.
- error
Incorrectly identifying the LCA when both nodes are in the same subtree.
- error
Not considering the edge case where one of the nodes is the root.
进阶变体
外企场景- arrow_right_alt
Find the LCA for multiple pairs of nodes in a single BST.
- arrow_right_alt
Find the LCA in a binary tree (not necessarily a BST).
- arrow_right_alt
Find the LCA in a tree with non-unique node values.