Java Solution with Recursion Easy-Understand


  • 0
    public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == p || root == q)
            return root;
        if(p == q)
            return p;
        Boolean pInLeft = inLeft(root.left, p);
        Boolean qInLeft = inLeft(root.left, q);
        if((pInLeft && !qInLeft) || (qInLeft && !pInLeft))
            return root;
        else if(qInLeft && pInLeft)
            return lowestCommonAncestor(root.left, p, q);
        else
            return lowestCommonAncestor(root.right, p, q);
    }
    
    public boolean inLeft(TreeNode root, TreeNode node){
        if(root == null)
            return false;
        if(root == node)
            return true;
        else
            return inLeft(root.left, node) || inLeft(root.right, node);
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.