问题
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。
说明:
- 所有节点的值都是唯一的。
- p、q 为不同节点且均存在于给定的二叉树中。
思路
最低的公共祖先,最简单的就是,这两个节点分别在 某节点 的左右两个子树上。只需要在左右子树上分别找这两个节点就行了。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || 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;
}
return root;
}
}
复杂度
-
时间复杂度:O(n)
-
空间复杂度:O(n)
解法二
代码
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode pParent = p;
TreeNode qParent = q;
while (pParent != null && qParent != null && pParent != qParent) {
TreeNode p1 = ancestor(pParent, qParent);
if (p1 != null) {
return pParent;
}
TreeNode p2 = ancestor(qParent, pParent);
if (p2 != null) {
return qParent;
}
pParent = ancestor(root, pParent);
qParent = ancestor(root, qParent);
}
return pParent;
}
private TreeNode ancestor(TreeNode root, TreeNode node) {
if (root == null) {
return null;
}
if (root == node || root.left == node || root.right == node) {
return root;
}
TreeNode left = ancestor(root.left, node);
if (left != null) {
return left;
}
TreeNode right = ancestor(root.right, node);
if (right != null) {
return right;
}
return null;
}
硬广告
欢迎关注公众号:double6
final
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情