Java Solution | with Explanation


  • 0
    S

    Basic idea is to check if both the given node p & q are of left , if so we need to traverse left node. Similarly, if both the nodes are of right then we have to traverse right of the root node.

    Base condition - when have our answer when one of the node is in left subtree and another in right subtree else part here ..

    public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        if(p == root || q == root) return root;
        TreeNode res = null;
        if(p.val <= root.val && q.val <= root.val){ 
            
            res = lowestCommonAncestor(root.left,p,q);
        }else if(p.val > root.val && q.val > root.val) {
            
            res = lowestCommonAncestor(root.right,p,q);
        }else{
            res = root;
        }       
    return res;
    

    }
    }


Log in to reply
 

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