Problems

Lowest Common Ancestor of a BST

medium
medium
binary-tree
binary-search-tree
depth-first-search

Given a BST and two values present in it, return the value of their lowest common ancestor.

Constraints

  • 2 <= number of nodes <= 10000
  • All node values are unique
  • p and q exist in the tree

Follow-up

How does BST ordering avoid a full tree traversal?

Execution note

Java/Go/Rust don't support this problem's ListNode/TreeNode structure yet — the starter is reference-only. Try Python or JavaScript to run and submit.

Examples

Example 1

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6

Example 2

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2

Example 3

Input: root = [2,1], p = 2, q = 1
Output: 2
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.