Smallest Stored Value That Is Not Below a Number
Solve this ProblemYou are given the root of a binary search tree with distinct values and an integer x. Return the smallest value in the tree that is greater than or equal to x (the "ceiling" of x). If every value in the tree is smaller than x, or the tree is empty, return -1.
Listing all values in order works, but the search-tree property lets you find the answer by walking a single path from the root and remembering the best candidate so far.
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 - ◆
0 ≤ x ≤ 1000 - ◆
Return the smallest value in the tree that is greater than or equal to x (x itself counts). If every value is smaller than x, or the tree is empty, 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 in Order, Then Find the First Big Enough
BruteAn inorder walk of a binary search tree visits the values in ascending order. Collect them all in a list, then scan from the smallest: the first value that is ≥ x is the smallest such value. If none qualifies, the answer is -1. It always builds the full list of n values: O(n) time and O(n) space.
O(n)O(n)1class Solution {
2 public int ceilOf(TreeNode root, int x) {
3 List<Integer> vals = new ArrayList<>();
4 inorder(root, vals);
5 for (int v : vals) {
6 if (v >= x) 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 — Walk Down Once, Remembering the Best Candidate
OptimalWalk down from the root, keeping best = the smallest value seen so far that is ≥ x (initially -1). If the current node equals x, that is the answer. If it is larger than x, it is a valid candidate — record it — and anything better must be smaller, so go LEFT. If it is smaller than x it is too small, and its whole left subtree is smaller still, so go RIGHT. When the walk runs off the tree, best holds the answer. Only one path is followed: O(h) time, O(1) space.
O(h)O(1)1class Solution {
2 public int ceilOf(TreeNode root, int x) {
3 int best = -1;
4 TreeNode cur = root;
5 while (cur != null) {
6 if (cur.val == x) return x;
7 if (cur.val > x) {
8 best = cur.val;
9 cur = cur.left;
10 } else {
11 cur = cur.right;
12 }
13 }
14 return best;
15 }
16}