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:
[Expected approach] By storing count of occurrence - O(h) Time and O(h) Space
A Better Solution is to augment every tree node to store count together with regular fields like key, and left and right pointers.
Insertion of keys 12, 10, 20, 9, 11, 10, 12, 12 in an empty Binary Search Tree would create following: Count of a key is shown in bracket.
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.
C++
// C++ program to implement basic operations // (search, insert, and delete) on a BST that// handles duplicates by storing count with // every node#include<bits/stdc++.h>usingnamespacestd;classNode{public:intkey;intcount;Node*left;Node*right;Node(intx){key=x;count=1;left=nullptr;right=nullptr;}};// A utility function to do inorder traversal of BSTvoidinorder(Node*root){if(root!=nullptr){inorder(root->left);cout<<root->key<<"("<<root->count<<") ";inorder(root->right);}}// A utility function to insert a new // node with given key in BST Node*insert(Node*node,intkey){// If the tree is empty, return a new nodeif(node==nullptr)returnnewNode(key);// If key already exists in BST, // increment count and returnif(key==node->key){node->count++;returnnode;}// Otherwise, recur down the treeif(key<node->key)node->left=insert(node->left,key);elsenode->right=insert(node->right,key);// return the (unchanged) node pointer returnnode;}// Given a non-empty binary search tree, return // the node with minimum key value found in that // tree. Note that the entire tree does not need// to be searched. Node*minValueNode(Node*node){Node*current=node;// loop down to find the leftmost leaf while(current->left!=nullptr)current=current->left;returncurrent;}// Given a binary search tree and a key, // this function deletes a given key and // returns root of modified tree Node*deleteNode(Node*root,intkey){// base caseif(root==nullptr)returnroot;// If the key to be deleted is smaller than the// root's key, then it lies in left subtreeif(key<root->key)root->left=deleteNode(root->left,key);// If the key to be deleted is greater than // the root's key, then it lies in right subtreeelseif(key>root->key)root->right=deleteNode(root->right,key);// if key is same as root's keyelse{// If key is present more than once, // simply decrement count and returnif(root->count>1){root->count--;returnroot;}// else, delete the node// node with only one child or no childif(root->left==nullptr){Node*curr=root->right;deleteroot;returncurr;}elseif(root->right==nullptr){Node*curr=root->left;deleteroot;returncurr;}// node with two children: Get the inorder // successor (smallest in the right subtree)Node*mn=minValueNode(root->right);// Copy the inorder successor's // content to this noderoot->key=mn->key;root->count=mn->count;// To ensure successor gets deleted by // deleteNode call, set count to 0.mn->count=0;// Delete the inorder successorroot->right=deleteNode(root->right,mn->key);}returnroot;}intmain(){// Let us create following BST// 12(3)// / \ // 10(2) 20(1)// / \ // 9(1) 11(1) Node*root=nullptr;root=insert(root,12);root=insert(root,10);root=insert(root,20);root=insert(root,9);root=insert(root,11);root=insert(root,10);root=insert(root,12);root=insert(root,12);cout<<"Inorder traversal of the given tree "<<endl;inorder(root);cout<<"\nDelete 20\n";root=deleteNode(root,20);cout<<"Inorder traversal of the modified tree \n";inorder(root);cout<<"\nDelete 12\n";root=deleteNode(root,12);cout<<"Inorder traversal of the modified tree \n";inorder(root);cout<<"\nDelete 9\n";root=deleteNode(root,9);cout<<"Inorder traversal of the modified tree \n";inorder(root);return0;}
C
// C program to implement basic operations // (search, insert, and delete) on a BST that// handles duplicates by storing count with // every node#include<stdio.h>#include<stdlib.h>structNode{intkey;intcount;structNode*left,*right;};structNode*createNode(intkey);// A utility function to do inorder traversal of BSTvoidinorder(structNode*root){if(root!=NULL){inorder(root->left);printf("%d(%d) ",root->key,root->count);inorder(root->right);}}// A utility function to insert a new node with given // key in BSTstructNode*insert(structNode*node,intkey){// If the tree is empty, return a new nodeif(node==NULL)returncreateNode(key);// If key already exists in BST, increment// count and returnif(key==node->key){node->count++;returnnode;}// Otherwise, recur down the treeif(key<node->key)node->left=insert(node->left,key);elsenode->right=insert(node->right,key);// return the (unchanged) node pointerreturnnode;}// Given a non-empty binary search tree, return// the node with minimum key value found in that treestructNode*minValueNode(structNode*node){structNode*current=node;// loop down to find the leftmost leafwhile(current&¤t->left!=NULL)current=current->left;returncurrent;}// Given a binary search tree and a key, this// function deletes a given key and returns the// root of modified treestructNode*deleteNode(structNode*root,intkey){// base caseif(root==NULL)returnroot;// If the key to be deleted is smaller than // the root's key, it lies in left subtreeif(key<root->key)root->left=deleteNode(root->left,key);// If the key to be deleted is greater than the// root's key, it lies in right subtreeelseif(key>root->key)root->right=deleteNode(root->right,key);// if key is same as root's keyelse{// If key is present more than once, // decrement count and returnif(root->count>1){root->count--;returnroot;}// node with only one child or no childif(root->left==NULL){structNode*temp=root->right;free(root);returntemp;}elseif(root->right==NULL){structNode*temp=root->left;free(root);returntemp;}// node with two children: Get the inorder // successor (smallest in the right subtree)structNode*temp=minValueNode(root->right);// Copy the inorder successor's content to this noderoot->key=temp->key;root->count=temp->count;// Set the count to 0 to ensure successor // gets deleted by deleteNode calltemp->count=0;// Delete the inorder successorroot->right=deleteNode(root->right,temp->key);}returnroot;}structNode*createNode(intkey){structNode*node=(structNode*)malloc(sizeof(structNode));node->key=key;node->count=1;node->left=node->right=NULL;returnnode;}intmain(){// Let us create following BST// 12(3)// / \ // 10(2) 20(1)// / \ // 9(1) 11(1) structNode*root=NULL;root=insert(root,12);root=insert(root,10);root=insert(root,20);root=insert(root,9);root=insert(root,11);root=insert(root,10);root=insert(root,12);root=insert(root,12);printf("Inorder traversal of the given tree\n");inorder(root);printf("\nDelete 20\n");root=deleteNode(root,20);printf("Inorder traversal of the modified tree\n");inorder(root);printf("\nDelete 12\n");root=deleteNode(root,12);printf("Inorder traversal of the modified tree\n");inorder(root);printf("\nDelete 9\n");root=deleteNode(root,9);printf("Inorder traversal of the modified tree\n");inorder(root);return0;}
Java
// Java program to implement basic operations // (search, insert, and delete) on a BST that// handles duplicates by storing count with // every nodeclassNode{intkey,count;Nodeleft,right;Node(intx){key=x;count=1;left=right=null;}}classGfG{// A utility function to do inorder traversal of BSTstaticvoidinorder(Noderoot){if(root!=null){inorder(root.left);System.out.print(root.key+"("+root.count+") ");inorder(root.right);}}// A utility function to insert a new // node with given key in BST staticNodeinsert(Nodenode,intkey){// If the tree is empty, return a new nodeif(node==null)returnnewNode(key);// If key already exists in BST, // increment count and returnif(key==node.key){node.count++;returnnode;}// Otherwise, recur down the treeif(key<node.key)node.left=insert(node.left,key);elsenode.right=insert(node.right,key);// return the (unchanged) node pointer returnnode;}// Given a non-empty binary search tree, return // the node with minimum key value found in that // tree. Note that the entire tree does not need// to be searched. staticNodeminValueNode(Nodenode){Nodecurrent=node;// loop down to find the leftmost leaf while(current.left!=null)current=current.left;returncurrent;}// Given a binary search tree and a key, // this function deletes a given key and // returns root of modified tree staticNodedeleteNode(Noderoot,intkey){// base caseif(root==null)returnroot;// If the key to be deleted is smaller than the// root's key, then it lies in left subtreeif(key<root.key)root.left=deleteNode(root.left,key);// If the key to be deleted is greater than // the root's key, then it lies in right subtreeelseif(key>root.key)root.right=deleteNode(root.right,key);// if key is same as root's keyelse{// If key is present more than once, // simply decrement count and returnif(root.count>1){root.count--;returnroot;}// else, delete the node// node with only one child or no childif(root.left==null){Nodetemp=root.right;root=null;returntemp;}elseif(root.right==null){Nodetemp=root.left;root=null;returntemp;}// node with two children: Get the inorder // successor (smallest in the right subtree)Nodetemp=minValueNode(root.right);// Copy the inorder successor's // content to this noderoot.key=temp.key;root.count=temp.count;// To ensure successor gets deleted by // deleteNode call, set count to 0.temp.count=0;// Delete the inorder successorroot.right=deleteNode(root.right,temp.key);}returnroot;}publicstaticvoidmain(String[]args){// Let us create following BST// 12(3)// / \// 10(2) 20(1)// / \// 9(1) 11(1) Noderoot=null;root=insert(root,12);root=insert(root,10);root=insert(root,20);root=insert(root,9);root=insert(root,11);root=insert(root,10);root=insert(root,12);root=insert(root,12);System.out.println("Inorder traversal of the given tree ");inorder(root);System.out.println("\nDelete 20");root=deleteNode(root,20);System.out.println("Inorder traversal of the modified tree ");inorder(root);System.out.println("\nDelete 12");root=deleteNode(root,12);System.out.println("Inorder traversal of the modified tree ");inorder(root);System.out.println("\nDelete 9");root=deleteNode(root,9);System.out.println("Inorder traversal of the modified tree ");inorder(root);}}
Python
# Python program to implement basic operations # (search, insert, and delete) on a BST that# handles duplicates by storing count with # every nodeclassNode:def__init__(self,key):self.key=keyself.count=1self.left=Noneself.right=None# A utility function to do inorder traversal of BSTdefinorder(root):ifrootisnotNone:inorder(root.left)print(f"{root.key}({root.count})",end=" ")inorder(root.right)# A utility function to insert a new # node with given key in BST definsert(node,key):# If the tree is empty, return a new nodeifnodeisNone:returnNode(key)# If key already exists in BST, # increment count and returnifkey==node.key:node.count+=1returnnode# Otherwise, recur down the treeifkey<node.key:node.left=insert(node.left,key)else:node.right=insert(node.right,key)# return the (unchanged) node pointer returnnode# Given a non-empty binary search tree, return # the node with minimum key value found in that # tree. Note that the entire tree does not need# to be searched. defminValueNode(node):current=node# loop down to find the leftmost leaf whilecurrent.leftisnotNone:current=current.leftreturncurrent# Given a binary search tree and a key, # this function deletes a given key and # returns root of modified tree defdeleteNode(root,key):# base caseifrootisNone:returnroot# If the key to be deleted is smaller than the# root's key, then it lies in left subtreeifkey<root.key:root.left=deleteNode(root.left,key)# If the key to be deleted is greater than # the root's key, then it lies in right subtreeelifkey>root.key:root.right=deleteNode(root.right,key)# if key is same as root's keyelse:# If key is present more than once, # simply decrement count and returnifroot.count>1:root.count-=1returnroot# ELSE, delete the node# node with only one child or no childifroot.leftisNone:temp=root.rightroot=Nonereturntempelifroot.rightisNone:temp=root.leftroot=Nonereturntemp# node with two children: Get the inorder # successor (smallest in the right subtree)temp=minValueNode(root.right)# Copy the inorder successor's # content to this noderoot.key=temp.keyroot.count=temp.count# To ensure successor gets deleted by # deleteNode call, set count to 0.temp.count=0# Delete the inorder successorroot.right=deleteNode(root.right,temp.key)returnrootif__name__=="__main__":# Let us create following BST# 12(3)# / \# 10(2) 20(1)# / \# 9(1) 11(1) root=Noneroot=insert(root,12)root=insert(root,10)root=insert(root,20)root=insert(root,9)root=insert(root,11)root=insert(root,10)root=insert(root,12)root=insert(root,12)print("Inorder traversal of the given tree ")inorder(root)print()print("\nDelete 20")root=deleteNode(root,20)print("Inorder traversal of the modified tree ")inorder(root)print()print("\nDelete 12")root=deleteNode(root,12)print("Inorder traversal of the modified tree ")inorder(root)print()print("\nDelete 9")root=deleteNode(root,9)print("Inorder traversal of the modified tree ")inorder(root)print()
C#
// C# program to implement basic operations // (search, insert, and delete) on a BST that// handles duplicates by storing count with // every nodeusingSystem;classNode{publicintkey,count;publicNodeleft,right;publicNode(intx){key=x;count=1;left=right=null;}}classGfG{// A utility function to do inorder traversal of BSTstaticvoidinorder(Noderoot){if(root!=null){inorder(root.left);Console.Write(root.key+"("+root.count+") ");inorder(root.right);}}// A utility function to insert a new // node with given key in BST staticNodeinsert(Nodenode,intkey){// If the tree is empty, return a new nodeif(node==null)returnnewNode(key);// If key already exists in BST, // increment count and returnif(key==node.key){node.count++;returnnode;}// Otherwise, recur down the treeif(key<node.key)node.left=insert(node.left,key);elsenode.right=insert(node.right,key);// return the (unchanged) node pointer returnnode;}// Given a non-empty binary search tree, return // the node with minimum key value found in that // tree. Note that the entire tree does not need// to be searched. staticNodeminValueNode(Nodenode){Nodecurrent=node;// loop down to find the leftmost leaf while(current.left!=null)current=current.left;returncurrent;}// Given a binary search tree and a key, // this function deletes a given key and // returns root of modified tree staticNodedeleteNode(Noderoot,intkey){// base caseif(root==null)returnroot;// If the key to be deleted is smaller than the// root's key, then it lies in left subtreeif(key<root.key)root.left=deleteNode(root.left,key);// If the key to be deleted is greater than // the root's key, then it lies in right subtreeelseif(key>root.key)root.right=deleteNode(root.right,key);// if key is same as root's keyelse{// If key is present more than once, // simply decrement count and returnif(root.count>1){root.count--;returnroot;}// else, delete the node// node with only one child or no childif(root.left==null){Nodecurr=root.right;root=null;returncurr;}elseif(root.right==null){Nodecurr=root.left;root=null;returncurr;}// node with two children: Get the inorder // successor (smallest in the right subtree)Nodemn=minValueNode(root.right);// Copy the inorder successor's // content to this noderoot.key=mn.key;root.count=mn.count;// To ensure successor gets deleted by // deleteNode call, set count to 0.mn.count=0;// Delete the inorder successorroot.right=deleteNode(root.right,mn.key);}returnroot;}staticvoidMain(string[]args){// Let us create following BST// 12(3)// / \// 10(2) 20(1)// / \// 9(1) 11(1) Noderoot=null;root=insert(root,12);root=insert(root,10);root=insert(root,20);root=insert(root,9);root=insert(root,11);root=insert(root,10);root=insert(root,12);root=insert(root,12);Console.WriteLine("Inorder traversal of the given tree ");inorder(root);Console.WriteLine("\nDelete 20");root=deleteNode(root,20);Console.WriteLine("Inorder traversal of the modified tree ");inorder(root);Console.WriteLine("\nDelete 12");root=deleteNode(root,12);Console.WriteLine("Inorder traversal of the modified tree ");inorder(root);Console.WriteLine("\nDelete 9");root=deleteNode(root,9);Console.WriteLine("Inorder traversal of the modified tree ");inorder(root);}}
JavaScript
// JavaScript program to implement basic operations // (search, insert, and delete) on a BST that// handles duplicates by storing count with // every nodeclassNode{constructor(key){this.key=key;this.count=1;this.left=this.right=null;}}// A utility function to do inorder traversal of BSTfunctioninorder(root){if(root!=null){inorder(root.left);console.log(root.key+"("+root.count+") ");inorder(root.right);}}// A utility function to insert a new // node with given key in BST functioninsert(node,key){// If the tree is empty, return a new nodeif(node==null)returnnewNode(key);// If key already exists in BST, // increment count and returnif(key==node.key){node.count++;returnnode;}// Otherwise, recur down the treeif(key<node.key)node.left=insert(node.left,key);elsenode.right=insert(node.right,key);// return the (unchanged) node pointer returnnode;}// Given a non-empty binary search tree, return // the node with minimum key value found in that // tree. Note that the entire tree does not need// to be searched. functionminValueNode(node){letcurrent=node;// loop down to find the leftmost leaf while(current.left!=null)current=current.left;returncurrent;}// Given a binary search tree and a key, // this function deletes a given key and // returns root of modified tree functiondeleteNode(root,key){// base caseif(root==null)returnroot;// If the key to be deleted is smaller than the// root's key, then it lies in left subtreeif(key<root.key)root.left=deleteNode(root.left,key);// If the key to be deleted is greater than // the root's key, then it lies in right subtreeelseif(key>root.key)root.right=deleteNode(root.right,key);// if key is same as root's keyelse{// If key is present more than once, // simply decrement count and returnif(root.count>1){root.count--;returnroot;}// else, delete the node// node with only one child or no childif(root.left==null){lettemp=root.right;root=null;returntemp;}elseif(root.right==null){lettemp=root.left;root=null;returntemp;}// node with two children: Get the inorder // successor (smallest in the right subtree)lettemp=minValueNode(root.right);// Copy the inorder successor's // content to this noderoot.key=temp.key;root.count=temp.count;// To ensure successor gets deleted by // deleteNode call, set count to 0.temp.count=0;// Delete the inorder successorroot.right=deleteNode(root.right,temp.key);}returnroot;}// Let us create following BST// 12(3)// / \// 10(2) 20(1)// / \// 9(1) 11(1) letroot=null;root=insert(root,12);root=insert(root,10);root=insert(root,20);root=insert(root,9);root=insert(root,11);root=insert(root,10);root=insert(root,12);root=insert(root,12);console.log("Inorder traversal of the given tree ");inorder(root);console.log("\nDelete 20");root=deleteNode(root,20);console.log("Inorder traversal of the modified tree ");inorder(root);console.log("\nDelete 12");root=deleteNode(root,12);console.log("Inorder traversal of the modified tree ");inorder(root);console.log("\nDelete 9");root=deleteNode(root,9);console.log("Inorder traversal of the modified tree ");inorder(root);
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.