class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return root;
//判断根节点是否为公共祖先
if(root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left , p , q);
TreeNode right = lowestCommonAncestor(root.right , p , q);
//如果 left 和 rihgt 都不为空 说明 根节点 左右子树里各有一个 p q 所以公共祖先就是root了
if(left != null && right != null) return root;
//因为是从上往下找的 所以先找到的 就是公共节点
if(left != null && right == null) return left;
return right;
}
}