LCA in BST

Question (LC.235)

How can you use the sorted property of BST?

Code

// if LCA is guaranteed to exist, ez then
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (Math.min(p.val, q.val) > root.val) {
        return lowestCommonAncestor(root.right, p, q);
    } else if (Math.max(p.val, q.val) < root.val) {
        return lowestCommonAncestor(root.left, p, q);
    } else {
        return root;
    }
}

Last updated