Inorder Successor in BST

Medium Trees

root is the root of a binary search tree: every value in a node's left subtree is smaller than the node's own value, and every value in its right subtree is larger, so no two nodes hold the same value. p is one of the tree's nodes; the examples name it by its value.

Read the tree's values from the smallest to the largest. The successor of p is the node that comes right after p in that order: the node holding the smallest value larger than p's. It can be a descendant of p or one of its ancestors.

Return the successor of p, or null if p holds the largest value in the tree and no node comes after it.

Example 1

Input: root = [20,10,30,5,15,25,35,null,null,12,18], p = 10
Output: 12
20103051525351218

Read from the smallest to the largest, the values are 5, 10, 12, 15, 18, 20, 25, 30, 35. 12 comes right after 10.

Example 2

Input: root = [50,30,70,20,40,60,80], p = 40
Output: 50
50307020406080

Example 3

Input: root = [15,6,18,3,7,17,20], p = 20
Output: null
15618371720

Constraints

  • 1 ≤ number of nodes ≤ 10⁵
  • -10⁹ ≤ node.val ≤ 10⁹
  • the tree is a binary search tree, so no two nodes hold the same value
  • p is a node of the tree

More Trees

All Trees problems