LeetCode 236. 二叉树的最近公共祖先

class Solution {
    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);

        //如果 left、right 同为空,说明root的左右子树均不含p,q,返回空。
        if(left == null && right == null) return null;
        //如果left为空,right不为空,说明p、q 同在right中,返回right
        if(left == null) return right;
        //如果right为空,left不为空,说明p,q同在left中,返回left
        if(right == null) return left;
        //如果left、right 均不为空,说明p,q在root的俩侧,root是公共祖先,返回 root
        return root;
    }
}
原文地址:https://www.cnblogs.com/peanut-zh/p/13885900.html