The TreeMap
This chapter is about TreeMap, an implementation of the Map ADT as an AVL tree ordered by key. Its get, containsKey, put, and remove all run in .
After reading this chapter, you should be able to:
- Implement
TreeMapby adapting the search tree chapter’sBinarySearchTree, with each node holding a key and a value and the tree ordered by aComparablekey - Implement the four rotations as methods that return the new root of the rotated subtree
- Implement a
rebalancehelper that chooses the rotation from two balance factors - Add balancing to the recursive
putandremoveby rebalancing each node on the recursion’s way back up - Cache each node’s height and keep it correct through every change, so
putandremoverun in instead of - Trace a sequence of
TreeMapoperations, including the call stack of a recursiveputand the rotation it triggers - Iterate a
TreeMap’s keys and entries in ascending key order with the search tree’s in-order iterator - Choose among the linked, array, sorted-array, and tree implementations of the Map ADT for a given workload, from their operation costs and memory
You can download the accompanying code for this chapter: starter and solution.
Sections
- Using a Balanced Tree to Implement a Map
- Starting from the Search Tree
- Implementing get and containsKey
- Where Balancing Goes
- Rotations in Code
- The Rebalance Helper
- put, First Version
- Why Recomputing Height Is Slow
- Caching the Height
- Rotations Keep the Height
- put, Final Version
- Implementing remove
- Iterating in Key Order
- Tracing the TreeMap
- The Complete TreeMap
- Four Maps, Side by Side