Lowest Common Ancestor of a Binary Search Tree - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

πŸ“Œ Notes

  • p and q are present in the tree.
  • The tree is a BST with unique node values.
  • p β‰  q.

🧠 Main Idea

We exploit the BST property to find the Lowest Common Ancestor (LCA) by walking down from the root. At each step, let the currentNode have value currVal:

  • Both target values smaller: If p.val < currVal and q.val < currVal, the LCA must lie in the left subtree, so set currentNode = currentNode.left.
  • Both target values larger: If p.val > currVal and q.val > currVal, the LCA must lie in the right subtree, so set currentNode = currentNode.right.
  • Split or match: Otherwise (they are on different sides of currentNode or currentNode is one of them), currentNode is the LCA. Return it.

🧠 Correctness Intuition

In a BST where all values are unique, every value in the left subtree of a node is smaller than the node’s own value, and every value in the right subtree is larger. If both targets are on the same side, the current node cannot be their LCA (there exists a deeper common ancestor on that side), so we continue the search in that direction. The first node where either the paths to p and q diverge, or current node is one of them, is by definition their Lowest Common Ancestor.

Time Complexity

O(h), where h is the tree height β€” the longest possible path from the root down to the found LCA has a length of at most h βˆ’ 1.

Space Complexity

O(1) auxiliary space is used β€” an iterative walk that employs only a few scalar variables, with no recursion or additional data structures.

Visucodize editorial solution titled JS Solution for LeetCode's Lowest Common Ancestor of a Binary Search Tree coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree.