
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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++
- Largest BST in a Binary Tree in C++
- Check if a Binary Tree contains duplicate subtrees of size 2 or more 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
- Maximum Sum BST in Binary Tree in C++
- Check if a binary string has a 0 between 1s or not in C++
- C++ Program to Check Whether a given Binary Tree is a Full Binary Tree or not
- Program to find out if a BST is present in a given binary tree in Python
- Check if an array represents Inorder of Binary Search tree or not in Python
- Check if a given Binary Tree is SumTree in C++

Advertisements