Which Stored Value Comes Right After a Key
Implement successorOf
You are given the root of a binary search tree with distinct values and an integer key (the key need not be in the tree). Return the value that comes immediately after key in the ascending order of the tree's values — the smallest value strictly greater than key — or -1 if no value is greater.
A list of all values makes this a simple scan. Walking down the tree once and remembering the last node where you turned left finds it directly.
Example 1:
Input: root = [35,15,60,8,25,45,75,null,null,20,30,null,50], key = 25
Output: 30
Example 2:
Input: root = [35,15,60,8,25,45,75,null,null,20,30,null,50], key = 30
Output: 35
Example 3:
Input: root = [35,15,60,8,25,45,75,null,null,20,30,null,50], key = 75
Output: -1
+ 14 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes ≤ 100; all node values are distinct, 0 ≤ node.val ≤ 1000 - ●
The tree is a binary search tree (left subtree smaller, right subtree larger at every node), given by its root node - ●
key is any integer between 0 and 1000 (it does not have to be in the tree) - ●
Return the value that comes immediately after key when the tree's values are listed in ascending order — that is, the smallest value that is STRICTLY greater than key. If there is none, return -1
root =
key =