In a Binary Search Tree (BST), all keys in the left subtree of a key must be smaller and all keys in the right subtree must be greater. So a Binary Search Tree by definition has distinct keys. How can duplicates be allowed where every insertion inserts one more key with a value and every deletion deletes one occurrence?
[Naive approach] Insert duplicate element on right subtree - O(h) Time and O(h) Space
A Simple Solution is to allow the same keys on the right side (we could also choose the left side). For example consider the insertion of keys 12, 10, 20, 9, 11, 10, 12, 12 in an empty Binary Search Tree:
This approach has following advantages over above simple approach.
Height of tree is small irrespective of number of duplicates. Note that most of the BST operations (search, insert and delete) have time complexity as O(h) where h is height of BST. So if we are able to keep the height small, we get advantage of less number of key comparisons.
Search, Insert and Delete become easier to do. We can use same insert, search and delete algorithms with small modifications (see below code).
This approach is suited for self-balancing BSTs (AVL Tree, Red-Black Tree, etc) also. These trees involve rotations, and a rotation may violate BST property of simple solution as a same key can be in either left side or right side after rotation.
Follow the steps below to solve the problem:
Algorithm for Insert in BST:
If the tree is empty, create a new node with the given key.
Traverse the tree:
If the key is smaller than the current node's key, move to the left child, otherwise, move to the right child.
If the key matches the current node, increment the count.
Repeat the process recursively until the correct position is found, then insert the new node.
Algorithm for Delete in BST:
Traverse the tree to find the node with the given key.
If found, and the node's count is greater than 1,decrement the count and return.
If the node has no children or one child, replace it with the child.
If the node has two children, find its inorder successor, copy its key and count, then delete the successor node.
Below is implementation of normal Binary Search Tree with count with every key. This code basically is taken from code for insert and delete in BST. The changes made for handling duplicates are highlighted, rest of the code is same.
Output
Inorder traversal of the given tree
9(1) 10(2) 11(1) 12(3) 20(1)
Delete 20
Inorder traversal of the modified tree
9(1) 10(2) 11(1) 12(3)
Delete 12
Inorder traversal of the modified tree
9(1) 10(2) 11(1) 12(2)
Delete 9
Inorder traversal of the modified tree
10(2) 11(1) 12(2)
Time Complexity: O(h) for every operation, h is height of BST. Auxiliary Space: O(h) which is required for the recursive function calls.