
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Binary Tree (Not BST) Has Duplicate Values 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
#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.
Advertisements