LeetCode 236. 二叉树的最近公共祖先

236. 二叉树的最近公共祖先

解题思路

  1. 如果当前节点是空节点,返回 null
  2. 如果 p 或者 q 为根节点,返回根节点
  3. 分别递归查找左右子树中的 pq
  4. 若左右子树都非空,说明 pq 分居当前节点两侧,当前节点就是最近公共祖先,返回它
  5. 若只有一侧非空,说明 pq 都在这一侧,返回该侧的查找结果;两侧都空则返回 null

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) {
return null;
}

if(root == p || root == q) {
return root;
}

TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null) {
return root;
}
return left == null ? right : left;
}
}

LeetCode 236. 二叉树的最近公共祖先
https://sowink.cn/2026/02/08/LeetCode-236-二叉树的最近公共祖先/
作者
Xurx
发布于
2026年2月8日
许可协议