Simplest Java solution in 3 condition checking


  • 0
    N

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

        return LCA(root, p, q);
    }
    
    private TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
        if((p.val < root.val) && (q.val > root.val)) {
            return root;
        } else if((p.val < root.val) && (q.val < root.val)) {
            return LCA(root.left, p, q);
        } else if((p.val > root.val) && (q.val > root.val)) {
            return LCA(root.right, p, q);
        }
        else return root;
    }
    

    }

    '''


Log in to reply
 

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