Lowest Common Ancestor of a Binary Search Tree - rFronteddu/general_wiki GitHub Wiki

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA on Wikipedia: โ€œThe lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).โ€

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || p == null || q == null) {
            return null;
        }
        
        var cur = root;
        while(true) {
            if (p.val > cur.val && q.val > cur.val) {
                cur = cur.right; 
            } else if (p.val < cur.val && q.val < cur.val) {
                cur = cur.left;
            } else return cur;
        }
    }
}