#235.Lowest Common Ancestor of a Binary Search Tree [LeetCode Grind 75 in Java]

Kallol BairagiKallol Bairagi
1 min read
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //check on the left side
        if(root.val > p.val && root.val > q.val)
            return lowestCommonAncestor(root.left, p, q);
        //check on the right side
        if(root.val < p.val && root.val < q.val)
            return lowestCommonAncestor(root.right, p, q);

        return root;

    }
}
0
Subscribe to my newsletter

Read articles from Kallol Bairagi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kallol Bairagi
Kallol Bairagi