Quick revision
The short answer
A plain binary search tree has no way to stay balanced, so inserting keys in sorted order turns it into a linked list where get, put and remove are O(n). TreeMap uses a red-black tree, which uses colour rules and rotations to keep its height at most about 2 log2(n + 1), so get, put and remove are O(log n) in the worst case and iteration in key order is O(n). Red-black trees do fewer rotations per update than AVL trees at the cost of slightly taller trees, and the ordering comes from Comparable or a Comparator that should be consistent with equals.
What to remember
In this answer, we saw that a plain binary search tree degrades into a linked list with O(n) operations when keys arrive in sorted order. TreeMap's red-black tree uses colour rules, a black root, no red node with a red child and equal black height on every path, plus rotations, to keep its height at most about 2 log2(n + 1), so get, put and remove are O(log n) in the worst case and in-order iteration is O(n). Red-black trees rotate less than AVL trees on updates in exchange for slightly taller trees, and TreeMap's comparator decides key identity, so it should be consistent with equals.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A plain binary search tree has no way to stay balanced, so inserting keys in sorted order turns it into a linked list where get, put and remove are O(n). TreeMap uses a red-black tree, which uses colour rules and rotations to keep its height at most about 2 log2(n + 1), so get, put and remove are O(log n) in the worst case and iteration in key order is O(n). Red-black trees do fewer rotations per update than AVL trees at the cost of slightly taller trees, and the ordering comes from Comparable or a Comparator that should be consistent with equals.
Why this question is asked
TreeMap is the standard library's sorted map, and many of us use it for its ordered keys and range methods without thinking about what keeps it fast. Interviewers ask this question to see whether we understand why balance matters, what a red-black tree actually guarantees, and the less obvious rule that TreeMap trusts the comparator completely. In this answer, we will recap binary search trees, see how sorted input breaks a plain one, look at the red-black rules and what they guarantee, see rotations in action, compare with AVL trees, and finish with the comparator rule.
1A Quick Recap of Binary Search Trees
A binary search tree stores keys in nodes, each with at most two children, following one rule: every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is larger. To find a key, we start at the root and go left or right at each node depending on the comparison, so a lookup visits one node per level. The cost of every operation is therefore proportional to the height of the tree.
If the tree is balanced, with roughly equal numbers of nodes on each side at every level, the height is about log2(n): 20 levels for a million keys. Nothing in the basic rule keeps it balanced, though.
2How Sorted Input Breaks a Plain BST
Suppose we insert the keys 1, 2, 3, 4, 5 in that order into a plain BST. 1 becomes the root. 2 is larger, so it goes to the right of 1. 3 is larger than 1 and 2, so it goes to the right of 2. Every key goes to the far right, and the tree becomes a chain of five nodes leaning right: in effect a linked list. Searching for 5 visits all five nodes.
Sorted or nearly sorted input is common in practice: ids from a sequence, timestamps, data loaded from an ordered query. With a million sorted keys a plain BST has height one million, every operation is O(n), and a recursive implementation would overflow the stack.
| n | Plain BST height | Red-black tree height bound |
|---|---|---|
| 7 | 7 | at most 6, in practice 3 or 4 |
| 1,000 | 1,000 | at most about 20 |
| 1,000,000 | 1,000,000 | at most about 40, typically around 20 to 25 |
log2(n + 1); real trees are usually closer to log2(n).3The Red-Black Rules and Their Guarantee
A red-black tree is a binary search tree where every node also carries a colour, red or black, and the colours must follow a few rules. The root is black. A red node never has a red child. And every path from a node down to an empty position below the leaves passes through the same number of black nodes, which is called the node's black height.
These rules bound the height. The shortest possible path from the root to an empty position consists only of black nodes, say b of them. The longest possible path alternates black and red, because two reds cannot be adjacent, so it has at most 2b nodes. So no path is more than twice as long as any other, and working through the node counts gives a height of at most 2 log2(n + 1). For a million keys that is at most about 40 levels, and in practice trees are much closer to the ideal 20.
Because every operation follows one path from the root, get, put and remove are O(log n) in the worst case, whatever order the keys arrive in. Iterating over all entries in key order is an in-order walk that visits each node once, so it is O(n) in total; TreeMap's parent pointers let each step find the next entry in amortized constant time.
4Rotations: How the Tree Rebalances
When TreeMap inserts a key, it first places it like a plain BST would, as a new red node. If that creates a red node with a red parent, the tree fixes it on the way back up, either by recolouring nodes or by rotating. A rotation is a local rearrangement of three nodes that keeps the search order but changes which node is on top.
Take the sorted insertions 1, 2, 3 again. After 1 (black root) and 2 (red right child), inserting 3 as a red right child of 2 breaks the red-red rule. The fix is a left rotation at 1: 2 moves up to become the root, 1 becomes its left child and 3 stays its right child. Then 2 is coloured black and 1 and 3 red. The tree has height 2 instead of 3, and it still satisfies the search rule, since 1 < 2 < 3.
- Insert 3 as a red noderight child of red node 2
- Red child of a red parent?YesFix neededNoDone
- Is the uncle red?YesRecolour and move upNoRotate
- Rotate left at 12 becomes the root, 1 and 3 its children
- Recolour2 black, 1 and 3 red: height 2
5 steps in order. Play them, or step through them one at a time.
An insertion needs at most two rotations, plus some recolouring that may move up the tree, and a deletion at most three. That constant bound on rotations per update is one of the reasons red-black trees are popular in libraries.
5Red-Black Versus AVL Trees
An AVL tree is another self-balancing BST. It keeps a stricter rule: the heights of the two subtrees of any node differ by at most one. That makes AVL trees shorter, at most about 1.44 log2(n), so lookups visit slightly fewer nodes. The price is more rebalancing work on updates, since the stricter rule is broken more often, and a deletion can need rotations all the way up the tree.
Red-black trees accept a looser balance, height up to about twice the ideal, in exchange for fewer rotations per insert and delete. For a general-purpose map that is updated as often as it is read, that trade-off works well, which is why TreeMap, HashMap's tree bins and many other libraries use red-black trees.
6The Ordering Must Be Consistent With equals
TreeMap never calls equals() or hashCode(). It decides everything with compareTo() or the Comparator we give it: if compare(a, b) returns 0, TreeMap treats a and b as the same key. The Map interface, however, is defined in terms of equals. When the two disagree, TreeMap still works, but it no longer behaves like a normal Map.
Sometimes this is exactly what we want, as with case-insensitive keys. But a comparator that, say, compares only a person's last name will silently merge different people into one entry. So we make the comparator consistent with equals, adding tie-breaking fields with thenComparing, unless we deliberately want the merged behaviour.
7Follow-up questions
What is an AVL tree's trade-off?
An AVL tree keeps every node's two subtree heights within one of each other, so its height stays below about 1.44 log2(n), shorter than a red-black tree's bound of 2 log2(n + 1). Lookups are therefore slightly faster. The cost is more rebalancing on insert and especially on delete, where rotations can be needed at every level on the way up. AVL suits read-heavy workloads; red-black trees suit mixed read and write workloads, which is why general-purpose libraries prefer them.
Why not just use a HashMap?
HashMap is faster for plain lookups, O(1) on average, but it keeps no order. TreeMap gives sorted iteration and navigation methods such as firstKey, floorKey, ceilingKey, headMap and subMap, all in O(log n). If we need ordering or range queries, TreeMap is the right tool; if not, HashMap is.
Can a TreeMap have a null key?
Not with natural ordering, because compareTo on null throws NullPointerException. With a Comparator that handles null, such as Comparator.nullsFirst(Comparator.naturalOrder()), it can. Null values are allowed either way.
8Conclusion
In this answer, we saw that a plain binary search tree degrades into a linked list with O(n) operations when keys arrive in sorted order. TreeMap's red-black tree uses colour rules, a black root, no red node with a red child and equal black height on every path, plus rotations, to keep its height at most about 2 log2(n + 1), so get, put and remove are O(log n) in the worst case and in-order iteration is O(n). Red-black trees rotate less than AVL trees on updates in exchange for slightly taller trees, and TreeMap's comparator decides key identity, so it should be consistent with equals.
Open with
A plain binary search tree has no balancing, so its shape depends on insertion order. If keys arrive sorted, which is common with ids or timestamps, every key goes to the right and the tree becomes a linked list, so every operation is O(n).
Then, if they want more
TreeMap uses a red-black tree instead. Each node is red or black, the root is black, a red node cannot have a red child, and every path down to the leaves has the same number of black nodes.
Those rules mean the longest path is at most twice the shortest, so the height is at most about 2 log2 of n plus 1, around 40 for a million keys and usually closer to 20. That gives O(log n) worst-case get, put and remove, and in-order iteration is O(n).
When an insert or delete breaks a rule, the tree fixes it with recolouring and at most a couple of rotations, which are local rearrangements that keep the search order. Compared to AVL trees, red-black trees are a bit taller but rotate less on updates, which suits a general-purpose map.
One thing people miss is that TreeMap only uses compareTo or the Comparator, never equals, so the ordering should be consistent with equals, otherwise, for example, BigDecimal 1.0 and 1.00 collapse into one key.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Why does java.util.TreeMap use a red-black tree instead of a plain binary search tree...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/9ce89902d3/