思路:跟235思路差不多,都是判断左右子树是否存在p,q,如果左右子树分别存在pq,则直接返回当前root,如果不存在,则继续递归左右子树
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
if(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; //如果左右都有,就返回当前root
return left != null ? left : right; //谁不为空,就返回谁
}