Lowest Common Ancestor of Binary Search Tree

Sneha Michelle,TreesDepth-First Search

Problem Link

Lowest Common Ancestor of Binary Search Tree (opens in a new tab)

Problem Statement


Algorithm

This is a binary search tree. It will always satisfy the rule: left<root<right

Code

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode curr = root;
        while (curr!=null){
            if (p.val>curr.val && q.val>curr.val){
                curr = curr.right;
            }
            else if ((p.val<curr.val && curr.val>q.val)){
                curr = curr.left; 
            }
            else{
                break;
            }
        }
        return curr;
    }
}