EASY NC#52 Blind #70 Trees

235. Lowest Common Ancestor of a Binary Search Tree

๐Ÿ“– Problem

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)."

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขMidpoint overflow-safe math
  • โ€ขLoop invariants
  • โ€ขMonotonic condition design

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Binary Search reasoning pattern

๐Ÿ’ก Approach

  • โ†’ BST property: left subtree < root < right subtree
  • โ†’ If both nodes are on same side, search that side
  • โ†’ If nodes are on different sides or one equals root, root is LCA
  • โ†’ Time: O(h), Space: O(h) where h is tree height

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขBST property: left subtree < root < right subtree
  • โ€ขIf both nodes are on same side, search that side
  • โ€ขIf nodes are on different sides or one equals root, root is LCA

Common Pitfalls

  • โ€ขTime: O(h), Space: O(h) where h is tree height

๐Ÿงช Test Cases

Hidden tests on submit: 2

Test Case 1
Not run
Input:
_lowestCommonAncestor(_node1, _node2, _node3);
Expected:
{"val":6,"left":{"val":2,"left":{"val":0,"left":null,"right":null},"right":{"val":4,"left":{"val":3,"left":null,"right":null},"right":{"val":5,"left":null,"right":null}}},"right":{"val":8,"left":{"val":7,"left":null,"right":null},"right":{"val":9,"left":null,"right":null}}}
Test Case 2
Not run
Input:
_lowestCommonAncestor(_node1, _node2, _node2.right);
Expected:
{"val":2,"left":{"val":0,"left":null,"right":null},"right":{"val":4,"left":{"val":3,"left":null,"right":null},"right":{"val":5,"left":null,"right":null}}}
Test Case 3
Not run
Input:
_lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null);
Expected:
Computed from hidden reference

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit