Sub topic 10
Handling Duplicate Keys
This chapter assumes you can read the Node, search, insert, and delete code from the earlier chapters. It also assumes you are comfortable with recursion.
Why duplicates need a rule
The ordering property says smaller keys go left and larger keys go right. It says nothing about equal keys. If you insert 5 twice, the tree has no obvious place for the second 5. Any implementation has to pick a policy, and the policy must be the same in insert, search, and delete.
The insert from the earlier chapter ignores equal keys. That is correct for a set of unique keys, but it silently loses data if you are storing a collection that can repeat.
Policy 1: ignore the duplicate
Use this when you only need to know whether a key is present. Insertion returns the tree unchanged on an equal key. It is the simplest policy and keeps the strict property "left < node < right".
Policy 2: store a count in the node
Each node keeps one copy of the key plus a counter. The tree stays strictly ordered, and its height depends only on the number of distinct keys.
class CountNode:
def __init__(self, key):
self.key = key
self.count = 1
self.left = None
self.right = None
def insert(node, key):
if node is None:
return CountNode(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
else:
node.count += 1
return node
def inorder(node):
if node is not None:
yield from inorder(node.left)
for _ in range(node.count):
yield node.key
yield from inorder(node.right)
root = None
for k in [5, 3, 5, 7, 3, 5]:
root = insert(root, k)
print(list(inorder(root))) # [3, 3, 5, 5, 5, 7]Deletion changes too. Deleting a key with count > 1 only decrements the counter. The node is removed, using the three cases from the deletion chapter, only when the count reaches 1.
Use this policy when records with equal keys are interchangeable, such as word frequencies.
Policy 3: send equal keys to one side
Here you change the comparison so that equal keys go right:
def insert_right(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert_right(node.left, key)
else:
node.right = insert_right(node.right, key)
return nodeThis stores every item as its own node. That matters when equal keys carry different payloads, such as two orders with the same timestamp. The property becomes "left < node <= right".
Gotchas
- Mixed policies break search. If
insertsends equal keys right but a later rewrite ofdeleteassumes strict ordering, items can become unreachable. Document the invariant and test it. - Search finds only one match. With policy 3,
searchreturns the first node with the key. The other copies are in its right subtree. To find all of them, keep walking right and collect nodes whose key matches. - Many copies of one key make a tall tree. Under policy 3, inserting the same key n times builds a right-leaning chain of height n - 1, so each operation costs O(n). A count field avoids this.
- Validation must match the policy. A checker that requires
left < node < rightwill reject a valid policy 3 tree.
Choosing a policy
| Need | Policy |
|---|---|
| Membership test only | Ignore |
| Frequencies of identical items | Count |
| Distinct records sharing a key | Equal goes right |
Exercise
You insert 4, 4, 4, 4 into an empty tree using policy 3 (equal keys go right). What is the tree's height, and which policy would keep it at 0?
Show answer
Each 4 becomes the right child of the previous one, so the tree is a chain of four nodes with height 3. The count policy keeps a single node with count 4, so the height is 0.