Implementing Ceil in BST

easy

Given the root of a binary search tree and an integer key, return the ceil of key — the smallest value in the BST that is greater than or equal to key. If no such value exists, return -1.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Ceil is the smallest value that is >= key.
If the node is < key, only its right subtree can hold the ceil.
If the node is >= key, record it as a candidate and go left to try to find a smaller valid value.

Common doubts

A node >= key is valid, but a smaller value that's still >= key may sit in its left subtree — and we want the smallest.
When every value is smaller than key, so no candidate is ever recorded.
Floor is the largest value <= key: record when the node is <= key and go right instead.

Interview follow-ups

Mirror the logic: candidate when node <= key, then go right to find a larger valid value.
You'd have to scan all nodes (O(n)); the ordering is what makes it an O(height) descent.

Fun facts

  • Ceil and floor together let a BST answer 'nearest value' queries in O(height).
  • This best-candidate descent is the same shape as lower_bound / upper_bound on a sorted array.

Asked at

AmazonMicrosoftFlipkart
Frequently Sometimes Occasionally
Example 1
Input: root = [8, 4, 12, 2, 6, 10, 14], key = 5
Output: 6
The smallest value >= 5 in the tree is 6.
Example 2
Input: root = [8, 4, 12, 2, 6, 10, 14], key = 15
Output: -1
No value is >= 15.
Constraints

- The number of nodes is in the range [1, 10^5] - 1 <= Node.val <= 10^5 - root is a valid BST - 0 <= key <= 10^5

Solve this problem →