力扣236
class Solution
{
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
//lowestCommonAncestor函数实现的功能是找出p,q节点的最近公共祖先
if(root==null) return null;
//如果p,q其中一个为根节点,另一个为子节点,那么最近公共节点就是根节点
if(p.val==root.val||q.val==root.val) return root;
//如果在root的左子树中找到了这个最近公共祖先,把这个最近公共祖先节点保存下来
TreeNode left=lowestCommonAncestor(root.left,p,q);
//如果在root的右子树中找到了这个最近公共祖先,把这个最近公共祖先节点保存下来
TreeNode right=lowestCommonAncestor(root.right,p,q);
//left为空,right不为空,表示在root的右子树中找到了这个最近公共祖先,返回right即可
if(left==null&&right!=null) return right;
//left不为空,right为空,表示在root的左子树中找到了这个最近公共祖先,返回left即可
if(left!=null&&right==null) return left;
//如果在root的左子树和右子树中都没找到最近公共祖先,那就返回root
if(left!=null&right!=null) return root;
return null;//必须有返回值
}
}