Minimum element in BST
Minimum element in BST is a easy trees & bst problem solved with the bst basics pattern.
The best approach, optimal (follow left children), runs in O(h) time and O(1) space.
Below are 2 approaches in Java, from traverse everything up.
Problem
Return the smallest value in a binary search tree.
Examples
Example 1
- Input
root = [5, 4, 6, 3, null, null, 7, 1]- Output
1
Example 2
- Input
root = [9, null, 10, null, 11]- Output
9
Constraints
- The tree has
1to10^5nodes; it is a valid BST.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Traverse everything | O(n) | O(h) |
| Optimal (follow left children) | O(h) | O(1) |
1Traverse everything
O(n)O(h)Visit every node and keep the smallest value. Works on any binary tree but ignores the BST property.
- DFS all nodes; track min.
class Solution {
int minValue(TreeNode root) {
if (root == null) return Integer.MAX_VALUE;
return Math.min(root.val, Math.min(minValue(root.left), minValue(root.right)));
}
}2Optimal (follow left children)
O(h)O(1)The minimum of a BST is its leftmost node. Keep going left until there is no left child.
- while root.left != null: root = root.left.
- return root.val.
class Solution {
int minValue(TreeNode root) {
while (root.left != null) root = root.left;
return root.val;
}
}Edge cases to test
- The root is the minimum (no left child)
Hints
Hint 1
In a BST, everything smaller lies to the left.
FAQ
What is the best time complexity for Minimum element in BST?
Optimal (follow left children) runs in O(h) time and O(1) extra space.
Which pattern does Minimum element in BST use?
It is a trees & bst problem that uses the bst basics pattern. Other problems with the same pattern: Search in a Binary Search Tree, Insert into a Binary Search Tree.
Is there a brute force solution for Minimum element in BST?
Yes. Traverse everything takes O(n) time and O(h) space. Visit every node and keep the smallest value.
Which edge cases should I test for Minimum element in BST?
The root is the minimum (no left child).