二叉搜索树的最近公共祖先
题目链接:
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
235. 二叉搜索树的最近公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (Math.max(p.val, q.val) < root.val) {
return lowestCommonAncestor(root.left, p, q);
} else if (Math.min(p.val, q.val) > root.val) {
return lowestCommonAncestor(root.right, p, q);
} else {
return root;
}
}
}
二叉树的最近公共祖先
题目链接:
剑指 Offer 68 - II. 二叉树的最近公共祖先
236. 二叉树的最近公共祖先
面试题 04.08. 首个共同祖先
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 && right == null) {
return null;
} else if (left != null && right != null) {
return root;
} else if (left == null && right != null) {
return right;
} else { //left != null && right == null
return left;
}
}
}