Check if a Binary Tree ( not BST ) has duplicate values | C ++ Program to check duplicates in Binary Tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; If tree is empty , there are no duplicates . ; If current node 's data is already present. ; Insert current node ; Recursively check in left and right subtrees . ; To check if tree has duplicates ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } bool checkDupUtil ( 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 checkDupUtil ( root -> left , s ) || checkDupUtil ( root -> right , s ) ; } bool checkDup ( struct Node * root ) { unordered_set < int > s ; return checkDupUtil ( root , s ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; if ( checkDup ( root ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }