Minimum/maximum
Beginner · 6 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
In a binary search tree the smallest value is found by always going left until you can go no further, and the largest by always going right. No searching and no comparing is needed, so you get the cheapest and costliest item almost instantly.
Practical use cases
- Web app: Cheapest and priciest listing. A marketplace page shows "Price range: 199 to 24,999" at the top of search results. With listings in a search tree, the code walks only the left edge for the lowest and only the right edge for the highest. The banner appears at once even with 200,000 listings.
- Web app: Earliest and latest booking date. A hotel admin calendar needs the first and last booked date to set its scroll range. Bookings sit in a tree ordered by date, so two short walks give both ends. The calendar opens without scanning every booking. It also stays correct as bookings change.
- System: Ordered set functions and delete. The first() and last() functions of ordered sets and maps are this walk. The delete operation also uses it, because it needs the smallest value in a right-hand branch. It is a small helper that many bigger operations rely on.
The story: The Cheapest and Costliest Mango
At the Sunday fruit market, Mira's uncle sold mangoes arranged in a special stall: the middle crate had a medium-priced mango. Cheaper mangoes were placed on the crates to its left, and costlier mangoes to its right, and the same pattern repeated at every crate.
A customer asked, "Which is your cheapest mango?" The uncle did not search the whole stall. He started at the middle crate and kept walking left, left, left... until there was no crate further left. "This one. Nothing is cheaper than this."
Then another customer asked for the costliest, the one for the wedding sweets. The uncle again started in the middle and kept walking right until the stall ended. Two questions, two short walks. That is the trick for minimum and maximum in a BST: the minimum is the far-left node and the maximum is the far-right node. No crate is ever visited twice.
How to spot this problem, and where you need it
You repeatedly need the smallest or largest value in a changing ordered collection, and scanning everything each time wastes effort.
Signs you need it
- You call min() or max() over a big array on every request, and the cost grows with the data.
- The data is already in a search tree or ordered map but you are looping to find the ends.
- The task says "find the smallest key in a BST" or needs the minimum as a step in another operation such as delete.
Where to use it in a project
- Banners and filters showing lowest and highest price, date or score of a large collection.
- Setting limits for sliders, calendars and charts from the first and last item in an ordered store.
The solution
For the minimum, start at the top node and keep moving to the left child until there is no left child; that node is the smallest. For the maximum, keep moving to the right child. You never compare values, because the tree rule already guarantees that the ends hold the extremes.
Payoff: Before: scanning 200,000 listings each time. After: following about 17 links on one edge of the tree.
Explain it like I am 8
In a row of buckets sorted from small to big, the smallest one is at the very left end and the biggest at the very right end. In a BST, you reach them by only turning left (or only turning right) from the top.
How it works, step by step
- Minimum: start at the root and keep moving to the left child while it exists.
- The node with no left child is the minimum.
- Maximum: start at the root and keep moving to the right child while it exists.
- The node with no right child is the maximum. An empty tree has neither.
The code in four languages
PHP
<?php
class Node {
public ?Node $left = null;
public ?Node $right = null;
public function __construct(public int $val) {}
}
function insert(?Node $n, int $v): Node {
if ($n === null) return new Node($v);
if ($v < $n->val) $n->left = insert($n->left, $v);
else $n->right = insert($n->right, $v);
return $n;
}
function minimum(?Node $root): ?int {
if ($root === null) return null; // empty tree
$cur = $root;
while ($cur->left !== null) $cur = $cur->left; // keep going left
return $cur->val;
}
function maximum(?Node $root): ?int {
if ($root === null) return null;
$cur = $root;
while ($cur->right !== null) $cur = $cur->right; // keep going right
return $cur->val;
}
$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
echo 'min: ', minimum($root), ' max: ', maximum($root), PHP_EOL; // min: 1 max: 14
echo 'empty tree min: ', minimum(null) ?? 'none', PHP_EOL;JavaScript
class Node {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
function insert(n, v) {
if (n === null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
function minimum(root) {
if (root === null) return null; // empty tree
let cur = root;
while (cur.left !== null) cur = cur.left; // keep going left
return cur.val;
}
function maximum(root) {
if (root === null) return null;
let cur = root;
while (cur.right !== null) cur = cur.right; // keep going right
return cur.val;
}
let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
console.log('min: ' + minimum(root) + ' max: ' + maximum(root)); // min: 1 max: 14
console.log('empty tree min: ' + (minimum(null) ?? 'none'));Java
public class Main {
static class Node {
int val;
Node left, right;
Node(int val) { this.val = val; }
}
static Node insert(Node n, int v) {
if (n == null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
static Integer minimum(Node root) {
if (root == null) return null; // empty tree
Node cur = root;
while (cur.left != null) cur = cur.left; // keep going left
return cur.val;
}
static Integer maximum(Node root) {
if (root == null) return null;
Node cur = root;
while (cur.right != null) cur = cur.right; // keep going right
return cur.val;
}
public static void main(String[] args) {
Node root = null;
for (int v : new int[]{8, 3, 10, 1, 6, 14, 4, 7, 13}) root = insert(root, v);
System.out.println("min: " + minimum(root) + " max: " + maximum(root)); // min: 1 max: 14
Integer none = minimum(null);
System.out.println("empty tree min: " + (none != null ? none : "none")); // none
}
}Go
package main
import "fmt"
type Node struct {
val int
left, right *Node
}
func insert(n *Node, v int) *Node {
if n == nil {
return &Node{val: v}
}
if v < n.val {
n.left = insert(n.left, v)
} else {
n.right = insert(n.right, v)
}
return n
}
// minimum returns the smallest key; ok is false for an empty tree.
func minimum(root *Node) (int, bool) {
if root == nil {
return 0, false // empty tree
}
cur := root
for cur.left != nil { // keep going left
cur = cur.left
}
return cur.val, true
}
func maximum(root *Node) (int, bool) {
if root == nil {
return 0, false
}
cur := root
for cur.right != nil { // keep going right
cur = cur.right
}
return cur.val, true
}
func main() {
var root *Node
for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
root = insert(root, v)
}
lo, _ := minimum(root)
hi, _ := maximum(root)
fmt.Println("min:", lo, "max:", hi) // min: 1 max: 14
if _, ok := minimum(nil); !ok {
fmt.Println("empty tree min: none")
}
}Time: O(h) · Extra space: O(1). One straight walk down the left (or right) edge, so the cost is the tree height.
Watch out for
- Searching the whole tree for the minimum like in an unsorted tree. The BST shape already tells you where it is.
- Assuming the minimum is a leaf. It can have a right child; it only has no left child.
- Crashing on an empty tree. Check for null first.
Quick check
- Where is the minimum of a BST?
- At the root
- Far left: keep going to the left child
- Far right
- Maximum of our tree?
- 10
- 13
- 14
- How many steps does the minimum walk take in a balanced tree of a million keys, roughly?
- About a million
- About twenty
- Exactly one