Easily understandable 3l Java code 9ms

  • 0

    The logic is to recurse until the two nodes split from the root.
    If both the values are less than root then both the nodes must be on left side of the root & vice versa.
    Whenver this condition doesn't satisfy that means the nodes are going in different directions which means we have found our lowest common ancestor.
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
        if(root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
        return root;


Log in to reply

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