How does insert(key, value) work in a binary search tree?
Search for the key with TreeSearch. If the search ends at an external node w, the key is new: store it in w and expand w into an internal node with two new external children. If the search finds the key, a map replaces the value instead.
- Search.
w = TreeSearch(key, root). - New key (w is external): write key and value into w and give it two new external children. w is now an internal node, exactly where the ordering property demands.
- Existing key (w is internal): in a map, which allows each key once, overwrite w's value.
Example: in the tree 6 → (2, 9), 2 → (1, 4), 9 → (8), insert(5) searches 6 → 2 → 4 and ends at 4's right external node, so 5 becomes the right child of 4.
Why is this position correct? Every comparison along the search path is a constraint that the new key satisfies: 5 < 6 put it in 6's left subtree, 5 > 2 in 2's right subtree, 5 > 4 in 4's right subtree. The external node at the end is the unique spot that meets all of them.
The cost is that of the search, $O(h)$; expanding the node is $O(1)$. A new key always becomes a leaf (an internal node with two external children); insertion never restructures the tree.
* The search ends at the gap where 5 belongs; that external node becomes internal. *
Go deeper:
Binary search tree: insertion — insertion as a search that ends in a new leaf, with pseudocode.