C++ program to print duplicate elements from the binary search tree
Description:
This Program is to find the duplicate element from the binary search tree.
For example:
Input tree : 4,4,5,6,8,7
Output :
Duplicate element is there for : 4
No duplicate element of : 5
No duplicate element of : 6
No duplicate element of : 7
No duplicate element of : 8
Program :
//C++ program to print duplicate elements from the binary search tree#include<bits/stdc++.h>usingnamespacestd;
// tree nodstructNode
{int data;
int key ,count;
Node *left, *right;
};
// returns a new tree NodeNode* newNode(int data){
structNode *temp = (structNode *)malloc(sizeof(structNode));
temp->key = data;
temp->left = temp->right = NULL;
temp->count = 1;
return temp;
}
// A function to create binary search tree.Node* Tree(Node* temp, int key ){
// If the tree is empty, return a new nodeif (temp == NULL)
return newNode(key);
if (key == temp->key)
{
(temp->count)++;
return temp;
}
// Otherwise, recur down the treeif (key < temp->key)
temp->left = Tree(temp->left, key);
else
temp->right = Tree(temp->right, key);
//return the (unchanged) node pointerreturn temp;
}
//function to display all the element present in the binary search treevoiddisplay(struct Node* root){
if (root != NULL)
{
display(root->left);
if(root->count>1)
{
cout<<"Duplicate element is there for : "<<root->key<<endl;
}
elsecout<<"No duplicate element of : "<<root->key<<endl;
display(root->right);
}
}
intmain(){
char ch;
int n, arr[20],size;
Node *root = new Node;
root = NULL;
cout<<"Enter the size of array : ";
cin>>size;
cout<<"Enter the elements in array : ";
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
// Construct the binary tree.for(int i = 0; i < size; i++)
{
root = Tree(root, arr[i]);
}
display(root);
return0;
}
Comments