The Binary Search Tree
This chapter is about the binary search tree. A binary search tree is a binary tree in which every value in a node’s left subtree is smaller than the node’s value and every value in its right subtree is larger, so a search can rule out one subtree with each comparison.
After reading this chapter, you should be able to:
- Decide whether a binary tree is a binary search tree by checking each value against all of its ancestors
- Search, add, and remove values in a binary search tree by hand, including removing a node with two children through its in-order successor
- Implement search, add, and remove with a public method and a private recursive helper
- Trace search, add, and remove as a call stack that grows down the search path and unwinds back to the root
- Explain why an in-order traversal of a binary search tree visits its values in ascending order
- Implement an in-order iterator for a binary search tree with an explicit stack that pauses between calls to
next - Analyze the tree’s operations in terms of its height : for search, add, and remove, and amortized per call to the iterator’s
next - Derive that a binary search tree with nodes has a height between about and
- Explain that adding values in sorted order builds a degenerate tree
You can download the accompanying code for this chapter: starter and solution.
Sections
- The Ordering Property
- The Node and the Tree
- Searching for a Value
- Search in Code
- Tracing a Search
- Adding a Value
- Add in Code
- Tracing an Add
- In-order Is Sorted
- Minimum, Maximum, and Successor
- Removing a Leaf or a Single Child
- Removing a Node with Two Children
- Remove in Code
- Tracing a Remove
- Iterating in Sorted Order
- Tracing the Iterator
- The Cost of the Iterator
- How Short Can a Tree Be?