二叉树
public class Solution
{
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
if(root==null || p==root || q==root) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left!=null && right!=null) return root;
return left==null ? right:left;
}
}
二叉搜索树
public class Solution
{
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
if(root==null || p==null || q==null) return null;
if(Math.max(p.val, q.val) < root.val) return lowestCommonAncestor(root.left, p, q);
if(Math.min(p.val, q.val) > root.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
}