What happens when a key that is already in the tree is inserted again, in a map and in a multimap?
In a map, which holds each key at most once, the existing entry's value is replaced. In a multimap, which may hold a key several times, either the node stores a list of values, or the search continues past the equal node into its left subtree and the duplicate is inserted there as a new node.
| Structure | What insert(k, v) does for an existing key k |
|---|---|
| Map | overwrite the value stored with k |
| Multimap, variant 1 | the node keeps a list of values; append v to it |
| Multimap, variant 2 | continue TreeSearch in the equal node's left subtree and insert a new node there |
Variant 2 example: in 6 → (2, 9), 2 → (1, 4), insert(2) finds 2, keeps searching in its left subtree, goes right from 1 (2 > 1) and ends at 1's right external node. The second 2 becomes the right child of 1.
That position still satisfies the ordering property, which is why it uses ≤ / ≥ rather than strict inequalities: the new 2 is in the old 2's left subtree (2 ≤ 2) and in 1's right subtree (2 ≥ 1). An inorder traversal then lists both 2s next to each other: 1, 2, 2, 4, 6, …
Go deeper:
Multimap — the abstract data type that allows several values per key, and how libraries implement it.