BSTs in practice
After this: Choose between a BST and a hash map, and name TreeMap, TreeSet and bisect.
On this page · 5 sections · 3 checks
You have built a BST by hand, and you know that its shape matters. In real work you will probably never write one. You will use one that a library gives you, or you will choose a different structure. This lesson shows how to decide, and what Python and Java offer.
BST or hash map?
Both structures store keys and find them again. Ask one question to choose: do you need order?
Here are two small examples.
- A price list where you look up the price of one product by its name. You always know the exact key, so you do not need order. Use a hash map.
- A list of booking times where you ask "what is the first booking after 14:00?". The key 14:00 may not exist, and you want the nearest key. That is a question about order. Use a BST.
Questions about order include the nearest key, the smallest or largest key, every key in a range, and all keys in sorted order. If you only need to find exact keys, a hash map is faster and simpler. The hash-maps tutorial showed that it finds a key in O(1) on average, which means the work stays about the same however many keys there are. A balanced BST costs O(log n), which grows slowly with the number of keys. That small extra cost is the price of keeping keys in order.
Java: TreeMap and TreeSet
If you write Java, you already have a balanced BST. TreeMap and TreeSet are red-black trees, the self-balancing trees from Why the shape matters. A single key lookup, insert or delete is O(log n). That is slower than the O(1) average of HashMap, but these classes answer the questions that a hash map cannot.
| Question | TreeMap / TreeSet | Cost |
|---|---|---|
| Is the key there? | containsKey(k) / contains(k) | O(log n) |
| Add or remove | put(k, v) / add(k), remove(k) | O(log n) |
| Smallest, largest | firstKey(), lastKey() / first(), last() | O(log n) |
| Nearest key at or above x | ceilingKey(x) / ceiling(x) | O(log n) |
| Nearest key at or below x | floorKey(x) / floor(x) | O(log n) |
| Everything from a up to b | subMap(a, b) / subSet(a, b) (a included, b excluded; the four-argument forms set both ends) | O(log n) to find the start, then one step per key |
| Go through in order | keySet() / the set itself | O(n) |
Python: nothing built in
Python's standard library has no BST. dict and set are hash tables, and dict keeps the order you inserted keys in, which is not sorted order. When you need order, you have three options.
- Keep a list sorted, and search it with
bisect. This suits data that rarely changes, because eachinsorthas to move O(n) items. - Call
sorted()each time you need order. This costs O(n log n) each time, which is about n × log₂ n steps. - Install the
sortedcontainerspackage. ItsSortedListandSortedDictgive you the same operations asTreeMap, at about O(log n) each.
The next block adds seven keys, keeps them in order, and then asks for the smallest key at or above 45, and for the keys from 35 to 65.
import bisect
keys = [] # no built-in BST: a sorted list stands infor k in [50, 30, 70, 20, 40, 60, 80]: bisect.insort(keys, k) # finds the spot in O(log n), shifts the rest in O(n)print(keys)print(keys[bisect.bisect_left(keys, 45)]) # the smallest key >= 45print(keys[bisect.bisect_left(keys, 35):bisect.bisect_right(keys, 65)])[20, 30, 40, 50, 60, 70, 80] 50 [40, 50, 60]
TreeSet<Integer> keys = new TreeSet<>(); // a red-black tree: a BST that keeps itself balancedfor (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) keys.add(k); // O(log n) eachSystem.out.println(keys);System.out.println(keys.ceiling(45)); // the smallest key >= 45, O(log n)System.out.println(keys.subSet(35, true, 65, true));[20, 30, 40, 50, 60, 70, 80] 50 [40, 50, 60]
The last block is about a map from names to prices. It prints the keys in sorted order, then the first key at or after "b".
prices = {"pear": 3, "apple": 2, "fig": 5} # a dict is a hash map: it has no sorted orderprint(sorted(prices)) # sort when you need order: O(n log n) every timeprint(min(k for k in prices if k >= "b")) # the first key at or after "b": a full scan['apple', 'fig', 'pear'] fig
TreeMap<String, Integer> prices = new TreeMap<>(); // keys kept in order by a red-black treeprices.put("pear", 3);prices.put("apple", 2);prices.put("fig", 5);System.out.println(prices.keySet()); // already in key orderSystem.out.println(prices.ceilingKey("b")); // the first key at or after "b": O(log n)[apple, fig, pear] fig
Check yourself
A leaderboard must find the lowest score above 1,000, list players from lowest to highest score, and keep accepting new scores all day. Which structure fits?
What are Java's TreeMap and TreeSet built on, and what does Python offer?
Seven keys go into an ordered container, then the code asks two questions about order. What does this print?
import bisect
keys = [] # no built-in BST: a sorted list stands infor k in [50, 30, 70, 20, 40, 60, 80]: bisect.insort(keys, k) # finds the spot in O(log n), shifts the rest in O(n)print(keys)print(keys[bisect.bisect_left(keys, 45)]) # the smallest key >= 45print(keys[bisect.bisect_left(keys, 35):bisect.bisect_right(keys, 65)])TreeSet<Integer> keys = new TreeSet<>(); // a red-black tree: a BST that keeps itself balancedfor (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) keys.add(k); // O(log n) eachSystem.out.println(keys);System.out.println(keys.ceiling(45)); // the smallest key >= 45, O(log n)System.out.println(keys.subSet(35, true, 65, true));Connect
- Answer 'BST or hash map?' by asking 'do you need order?'
- Use Java's TreeMap and TreeSet for questions about order at O(log n), knowing that they are red-black trees.
- Say that Python has no built-in BST, and choose between sorted(), bisect and sortedcontainers.