Check if a Binary Tree (not BST) has duplicate value in C++


Consider we have a binary tree, this binary tree is not a BST. We have to check whether the binary tree contains same element more than one time or not. To solve this, we will use hashing. We will traverse the given tree, for each node, we will check whether the node is present in the table or not, if that is already present, then return false, otherwise true.

Example

 Live Demo

#include <iostream>
#include <unordered_set>
using namespace std;
class Node {
   public:
   int data;
   Node *left;
   Node *right;
};
Node* getNode(int data){
   Node *newNode = new Node;
   newNode->data = data;
   newNode->left = NULL;
   newNode->right = NULL;
   return newNode;
}
bool hasDuplicateHelper(Node *root, unordered_set<int> &s){
   if(root == NULL)
      return false;
   if (s.find(root->data) != s.end())
      return true;
   s.insert(root->data);
   return hasDuplicateHelper(root->left, s) ||  hasDuplicateHelper(root->right, s);
}
bool hasDuplicate(Node *root){
   unordered_set<int> s;
   return hasDuplicateHelper(root, s);
}
int main() {
   Node *root = getNode(10);
   root->left = getNode(20);
   root->right = getNode(20);
   root->left->left = getNode(30);
   if (hasDuplicate(root))
      cout << "The tree has duplicate elements.";
   else
      cout << "The tree has no duplicate elements.";
}

Output

The tree has duplicate elements.

Updated on: 22-Oct-2019

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements