注意:递归返回的是最下层满足条件的结点,找到这个最下层最先满足条件的结点(这个结点就是最近公共祖先),然后通过递归一路向上返回(递归的作用体现在这)。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return myLowestCommonAncestor(root,p,q);
}
public TreeNode myLowestCommonAncestor(TreeNode root,TreeNode p,TreeNode q)
{
if(root==null || root==q || root==p)
{
return root;
}
TreeNode left=myLowestCommonAncestor(root.left,p,q); //在左子树找p和q
TreeNode right=myLowestCommonAncestor(root.right,p,q); //在右子树找p和q
if(left!=null && right!=null) //说明左右子树各找到p和q当中的一个,那么p和q在root的两侧
{
return root; //从最下层开始,返回最先满足条件的结点
}
else if(left!=null) //说明p和q在左子树里面
{
return left; //从最下层开始,返回最先满足条件的结点
}
else if(right!=null) //说明p和q在右子树里面
{
return right; //从最下层开始,返回最先满足条件的结点
}
else //说明找不到
{
return null;
}
}
}