Recursive Simple Java Solution.


  • 0
    J

    class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == p || root == q || root == null) return root;

        boolean is_p_on_left = includes(root.left, p);
        boolean is_q_on_left = includes(root.left, q);
        
        if(is_p_on_left != is_q_on_left) return root;
        
        return is_p_on_left ? lowestCommonAncestor(root.left, p, q):lowestCommonAncestor(root.right, p, q);
    }
    
    public boolean includes(TreeNode root, TreeNode node) {
        if(root == null) return false;
        if(root == node) return true;
        
        return includes(root.left, node) || includes(root.right, node);
    }
    

    }


Log in to reply
 

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