Which Stored Value Comes Right After a Key
Solve this ProblemYou 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.
Test Case 1:
Test Case 2:
Test Case 3:
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
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — List All Values, Take the First One Above the Key
BruteAn inorder walk gives the tree's values in ascending order. Collect them in a list and scan from the smallest: the first value that is strictly greater than the key is the one that comes right after it (whether or not the key itself is in the tree). If none is greater, the answer is -1. It walks every node and stores all n values: O(n) time and O(n) space.
O(n)O(n)1class Solution {
2 public int successorOf(TreeNode root, int key) {
3 List<Integer> vals = new ArrayList<>();
4 inorder(root, vals);
5 for (int v : vals) {
6 if (v > key) return v;
7 }
8 return -1;
9 }
10
11 private void inorder(TreeNode node, List<Integer> vals) {
12 if (node == null) return;
13 inorder(node.left, vals);
14 vals.add(node.val);
15 inorder(node.right, vals);
16 }
17}Optimal — Descend Once, Remembering the Last Node Where We Turned Left
OptimalWalk down from the root. If the current node's value is greater than the key, it is a candidate for "the next value after the key" — remember it — and a smaller candidate could only be in its LEFT subtree, so go left. If the current node's value is not greater than the key, neither it nor anything in its left subtree can qualify, so go RIGHT. When the path ends, the last remembered candidate is the successor (or -1 if none). This covers both cases at once: the leftmost node of the key's right subtree, or the nearest ancestor from which the path turned left. O(h) time, O(1) space.
O(h)O(1)1class Solution {
2 public int successorOf(TreeNode root, int key) {
3 int best = -1;
4 TreeNode cur = root;
5 while (cur != null) {
6 if (cur.val > key) {
7 best = cur.val;
8 cur = cur.left;
9 } else {
10 cur = cur.right;
11 }
12 }
13 return best;
14 }
15}