以树的遍历为载体,查找节点的公共祖先
至此,剑指Offer(第2版)刷题小记 告一段落。之后将继续更新力扣主站的刷题记录。

题目链接-来源:力扣(LeetCode)

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

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

例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4]

示例 1:

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

思路:

对比上题 BST,其未经优化的解法即是对应一般二叉树的通解。
时间复杂度:O(n)
空间复杂度:O(n)

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root == p || root == q) {
return root;
}
TreeNode l, r;
l = lowestCommonAncestor(root.left, p, q);
r = lowestCommonAncestor(root.right, p, q);
if (l != null && r != null) {
return root;
}
if (l != null) {
return l;
}
return r;
}
}