给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
示例 1:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3 。
示例 2:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出:5
解释:节点 5 和节点 4 的最近公共祖先是节点 5 。因为根据定义最近公共祖先节点可以为节点本身。
示例 3:
输入:root = [1,2], p = 1, q = 2
输出:1
提示:
树中节点数目在范围 [2, 105] 内。
-109 <= Node.val <= 109
所有 Node.val 互不相同 。
p != q
p 和 q 均存在于给定的二叉树中。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
感谢大佬数据结构和算法的详细解法java代码递归和非递归图文详解
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// return lowestCommonAncestorI(root, p, q);
return lowestCommonAncestorII(root, p, q);
}
//方法二:迭代
//定义hashmap记录每个节点的父节点
//从p节点开始向上回溯,记录其所有祖先节点
//再从q节点开始向上查找,直到找到一个节点是p的祖先节点为止,此时该节点就是p和q的最近公共祖先。
//时间复杂度O(n),空间复杂度O(n)
private TreeNode lowestCommonAncestorII(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
Map<TreeNode, TreeNode> parent = new HashMap<>();
//根节点不存在父节点
parent.put(root, null);
//没有必要遍历全部节点,只要找到两个节点就可以
while (!parent.containsKey(p) || !parent.containsKey(q)) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
parent.put(node.left, node);
}
if (node.right != null) {
queue.offer(node.right);
parent.put(node.right, node);
}
}
//记录p以及它的所有祖先节点
Set<TreeNode> ancestors = new HashSet<>();
while (p != null) {
ancestors.add(p);
p = parent.get(p);
}
//查看p和它的祖先节点是否包含q节点,如果不包含再看是否包含q的祖先节点
while (!ancestors.contains(q)) {
q = parent.get(q);
}
return q;
}
//方法一:递归
//时间复杂度O(n),空间复杂度O(n)
private TreeNode lowestCommonAncestorI(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) {
return right;
}
if (right == null) {
return left;
}
//如果左右子树中都找到了最近公共祖先,那么当前节点root就是最近公共祖先
return root;
}
}