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 root;
return left == null ? right : left;
}
本题的分为2种情况:
1.p是q的祖先或者q是p的祖先:
此时left和right有一个必定为null。假设p,q都在root的左子树,那么右子树是不可能找到p,q的,这个时候right为null,那么我们应该返回找到p或q的left,即返回left,right中不为空的那个节点,也就是最后一句代码return left == null ? right : left;
2.p,q分别在左右两边,则它们的祖先为left和right的父节点,即root:
这种情况left和right都不为null,因为都找到了p和q,那么我们应该返回root,也就是倒数第二句代码
if(left != null && right != null) return root;