THN Interview Prep

235. Lowest Common Ancestor of a BST

At a Glance

  • Topic: Binary Search Tree
  • Pattern: DFS
  • Difficulty: Easy
  • LeetCode: 235

Problem Statement

Find the lowest common ancestor (LCA) node of two given nodes in a BST.

Approach & Solution Steps

Leverage the BST property. If both target nodes are smaller than the current node, search the left subtree. If both are larger, search the right subtree. Otherwise, the current node is the LCA.

Optimal JS Solution

function lowestCommonAncestor(root, p, q) {
  let curr = root;
  while (curr) {
    if (p.val < curr.val && q.val < curr.val) curr = curr.left;
    else if (p.val > curr.val && q.val > curr.val) curr = curr.right;
    else return curr;
  }
  return null;
}

Edge Cases & Pitfalls

  • Always consider empty or null inputs.
  • Watch out for off-by-one index errors.

Mark this page when you finish learning it.

Last updated on

Spotted something unclear or wrong on this page?

On this page