Blind 75
29 / 75Free practice

Lowest Common Ancestor of a Binary Search Tree

Medium · Trees

Jump to code

In a BST with distinct values, find the lowest node whose subtree contains two given nodes p and q. A node may be its own ancestor; both targets exist.

Examples

Example 1

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

Output: 6

Example 2

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

Output: 2

Constraints

  • 2 <= The number of nodes in the tree <= 100
  • -100 <= Node.val <= 100
  • p != q
  • p and q will both exist in the BST

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

p and q refer to the existing nodes in root with those values.

Need a hint?

Use the ordering rule before exploring any children.

Asked in real interviews

Candidates reported versions of Lowest Common Ancestor of a Binary Search Tree from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    6,
    2,
    8,
    0,
    4,
    7,
    9,
    null,
    null,
    3,
    5
  ],
  2,
  8
]
Expected
6
Case 2
Input
[
  [
    6,
    2,
    8,
    0,
    4,
    7,
    9,
    null,
    null,
    3,
    5
  ],
  2,
  4
]
Expected
2
Case 3
Input
[
  [
    6,
    2,
    8,
    0,
    4,
    7,
    9,
    null,
    null,
    3,
    5
  ],
  3,
  5
]
Expected
4
Case 4
Input
[
  [
    6,
    2,
    8,
    0,
    4,
    7,
    9,
    null,
    null,
    3,
    5
  ],
  7,
  9
]
Expected
8
Case 5
Input
[
  [
    6,
    2,
    8,
    0,
    4,
    7,
    9,
    null,
    null,
    3,
    5
  ],
  6,
  8
]
Expected
6

Drafts are saved per language in this browser when storage is available.