Medium · Trees

Inorder Successor in BST

Given the root of a binary search tree with distinct values and a node p in it, return the node with the smallest value greater than p.val (p's in-order successor), or null if p holds the largest value.

Examples

Example 1

{
  "tree": [20, 8, 22, 4, 12, null, null, null, null, 10, 14],
  "p": 8
}

Output: successor = 10

Example 2

{
  "tree": [20, 8, 22, 4, 12, null, null, null, null, 10, 14],
  "p": 14
}

Output: successor = 20

Rebuild it in the studio

Core interview problems are free with a full runner and lessons; Pro opens the complete library.

More Trees problems