题目描述

题目链接:236. 二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

示例1:

img

1
2
3
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3

示例2:

img

1
2
3
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出:5
解释:节点 5 和节点 4 的最近公共祖先是节点 5 。因为根据定义最近公共祖先节点可以为节点本身。

示例3:

1
2
输入:root = [1,2], p = 1, q = 2
输出:1

提示:

  • 树中节点数目在范围 [2, 105] 内。
  • -109 <= Node.val <= 109
  • 所有 Node.val 互不相同 。
  • p != q
  • p 和 q 均存在于给定的二叉树中。

我的题解

方法一:层序遍历

思路

一个非常直观的思路是,从p、q两个节点向上找,找到第一个公共节点,即是最近公共祖先节点。因此我们先层序遍历,记录当前节点的前一节点,再向上查找第一个公共节点,代码如下:

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
TreeNode tp = null, tq = null;
HashMap<TreeNode, TreeNode> map = new HashMap<>();
while (!queue.isEmpty() && (tp == null || tq == null)) {
TreeNode poll = queue.poll();
if (poll.val == p.val) {
tp = poll;
}
if (poll.val == q.val) {
tq = poll;
}
if (poll.left != null) {
queue.offer(poll.left);
map.put(poll.left, poll);
}
if (poll.right != null) {
queue.offer(poll.right);
map.put(poll.right, poll);
}
}
HashSet<TreeNode> set = new HashSet<>();
while (tp != null) {
set.add(tp);
tp = map.get(tp);
}
while (tq != null && !set.contains(tq)) {
tq = map.get(tq);
}
return tq;
}
}

结果

执行用时:12 ms, 在所有 Java 提交中击败了6.96%的用户

内存消耗:42 MB, 在所有 Java 提交中击败了98.21%的用户

方法二:深度遍历

思路

一般对于这种题目,我们首先考虑最基本的情况:

  • p、q位于root左右两边,那当前节点就是最近公共祖先
  • root==p,q可能位于root左边或右边,那么当前节点就是最近公共祖先
  • root==q,p可能位于root左边或右边,那么当前节点就是最近公共祖先

因此,采用后序遍历:

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root.val == p.val || root.val == q.val) {
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 ? left : right;
}
}

结果

执行用时:6 ms, 在所有 Java 提交中击败了99.99%的用户

内存消耗:42.9 MB, 在所有 Java 提交中击败了39.74%的用户