Check if a Binary Tree ( not BST ) has duplicate values | Java Program to check duplicates in Binary Tree ; Function that used HashSet to find presence of duplicate nodes ; 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 ; A binary tree Node has data , pointer to left child and a pointer to right child
import java . util . HashSet ; public class CheckDuplicateValues { public static boolean checkDupUtil ( Node root , HashSet < Integer > s ) { if ( root == null ) return false ; if ( s . contains ( root . data ) ) return true ; s . add ( root . data ) ; return checkDupUtil ( root . left , s ) || checkDupUtil ( root . right , s ) ; } public static boolean checkDup ( Node root ) { HashSet < Integer > s = new HashSet < > ( ) ; return checkDupUtil ( root , s ) ; } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 2 ) ; root . left . left = new Node ( 3 ) ; if ( checkDup ( root ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } } class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; } } ;