

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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
#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.
- Related Questions & Answers
- A program to check if a binary tree is BST or not in C ?
- C++ Program to Check if a Binary Tree is a BST
- Program to check whether a binary tree is BST or not in Python
- Check if a binary tree is sorted levelwise or not in C++
- Check if a binary string has a 0 between 1s or not in C++
- Largest BST in a Binary Tree in C++
- Check if a binary tree is sorted level-wise or not in C++
- Check if a binary tree is subtree of another binary tree in C++
- C++ program to Check if a Given Binary Tree is an AVL Tree or Not
- Check if a Binary Tree contains duplicate subtrees of size 2 or more in C++
- Maximum Sum BST in Binary Tree in C++
- Find if an expression has duplicate parenthesis or not in C++
- Check if a given Binary Tree is SumTree in C++
- Check if a given Binary Tree is Heap in C++
- C++ Program to Check Whether a given Binary Tree is a Full Binary Tree or not
Advertisements