 All Problems
Lowest Common Ancestor of a Binary Search Tree
medium
tree
depth-first search
binary search tree
binary tree
amazon
facebook
microsoft

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

The LCA is defined as the lowest node in the tree that has both p and q as descendants (a node is a descendant of itself).

Example 1:

Input:
6 2 8 0 4 7 9 null null 3 5
2
8
Output: 6

Example 2:

Input:
6 2 8 0 4 7 9 null null 3 5
2
4
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [2, 10⁵]
  • -10⁹ ≤ Node.val ≤ 10⁹
  • All Node.val are unique
  • p != q, both values exist in the BST

Input format: First line: BST in BFS level-order (null for missing). Second line: value of p. Third line: value of q.

Output format: The value of the LCA node.

Run to check your code against the sample cases, or submit to run every case