题目来源
题目概述
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
思路分析
之前写过类似的题力扣236二叉树的最近公共祖先,二叉搜索树也是二叉树,完全可以用一样的方法解题。 如果一个节点是目标节点的公共祖先节点,只存在两种情况:
- 这个节点就是目标节点
- 目标节点在这个节点的两棵子树中,一边一个。 其他的情况都无法说明当前节点为公共祖先。
代码实现
java实现
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// 空树
if (root == null) {
return null;
}
// 当前节点就是目标节点
if (root == p || root == q) {
return root;
}
// 左子树和右子树分别求出p和q的最近公共祖先
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
// 如果左子树和右子树都存在p和q的最近公共祖先,则root就是p和q的最近公共祖先
if (left != null && right != null) {
return root;
}
// 如果本节点的其中一棵子树是目标节点的公共祖先,继续向上返回找到的公共祖先
// q、p存在父子级关系,或者p、q在两棵更大的子树中
if (left != null || right != null) {
return left != null ? left : right;
}
// 如果左子树和右子树都不存在p和q的最近公共祖先,则root不是p和q的最近公共祖先
return null;
}
}
c++实现
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 空树
if (root == nullptr) {
return root;
}
// 当前节点就是目标节点
if (root == p || root == q) {
return root;
}
// 递归查询两棵子树中是否存在目标节点的公共祖先
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
// 如果本节点的两棵子树都是目标节点的公共祖先,则本节点是公共祖先
if (left != nullptr && right != nullptr) {
return root;
}
// 如果本节点的其中一棵子树是目标节点的公共祖先,继续向上返回找到的公共祖先
// q、p存在父子级关系,或者p、q在两棵更大的子树中
if (left != nullptr || right != nullptr) {
return left != nullptr ? left : right;
}
// 本树中不存在pq的公共祖先
return nullptr;
}
}