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
๐ค Output