Check if a Binary Tree (not BST) has duplicate values - GeeksforGeeks

31 Mar, 2022
Check if a Binary Tree (not BST) has duplicate valuesExamples:  
Input : Root of below tree
         1
       /   \
      2     3
             \
              2
Output : Yes
Explanation : The duplicate value is 2.

Input : Root of below tree
         1
       /   \
     20     3
             \
              4
Output : No
Explanation : There are no duplicates.
 
A simple solution is to store inorder traversal of given binary tree in an array. Then check if array has duplicates or not. We can avoid the use of array and solve the problem in O(n) time. The idea is to use hashing. We traverse the given tree, for every node, we check if it already exists in hash table. If exists, we return true (found duplicate). If it does not exist, we insert into hash table. 
C++
Java
Python
C#
Javascript
// C++ Program to check duplicates// in Binary Tree#include <bits/stdc++.h>using namespace std; // A binary tree Node has data,// pointer to left child// and a pointer to right childstruct Node {    int data;    struct Node* left;    struct Node* right;}; // Helper function that allocates// a new Node with the given data// and NULL left and right pointers.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 tree is empty, there are no    // duplicates.    if (root == NULL)       return false;     // If current node's data is already present.    if (s.find(root->data) != s.end())       return true;     // Insert current node    s.insert(root->data);         // Recursively check in left and right    // subtrees.    return checkDupUtil(root->left, s) ||           checkDupUtil(root->right, s);} // To check if tree has duplicatesbool checkDup(struct Node* root){    unordered_set<int> s;    return checkDupUtil(root, s);} // Driver program to test above functionsint 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;}
// Java Program to check duplicates// in Binary Treeimport java.util.HashSet;public class CheckDuplicateValues {     //Function that used HashSet to find presence of duplicate nodes    public static boolean checkDupUtil(Node root, HashSet<Integer> s)    {        // If tree is empty, there are no        // duplicates.         if (root == null)            return false;           // If current node's data is already present.        if (s.contains(root.data))            return true;           // Insert current node        s.add(root.data);               // Recursively check in left and right        // subtrees.        return checkDupUtil(root.left, s) || checkDupUtil(root.right, s);    }       // To check if tree has duplicates    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");    }} // A binary tree Node has data,// pointer to left child// and a pointer to right childclass Node {    int data;    Node left,right;    Node(int data)    {        this.data=data;    }};//This code is contributed by Gaurav Tiwari
""" Program to check duplicates# in Binary Tree """ # Helper function that allocates a new# node with the given data and None# left and right pointers.                                class newNode:     # Construct to create a new node    def __init__(self, key):        self.data = key        self.left = None        self.right = None def checkDupUtil( root, s) :     # If tree is empty, there are no    # duplicates.    if (root == None) :        return False     # If current node's data is already present.    if root.data in s:        return True     # Insert current node    s.add(root.data)         # Recursively check in left and right    # subtrees.    return checkDupUtil(root.left, s) or checkDupUtil(root.right, s)  # To check if tree has duplicatesdef checkDup( root) :     s=set()    return checkDupUtil(root, s)  # Driver Codeif __name__ == '__main__':    root = newNode(1)    root.left = newNode(2)    root.right = newNode(2)    root.left.left = newNode(3)    if (checkDup(root)):        print("Yes")    else:        print("No") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# Program to check duplicates// in Binary Treeusing System;using System.Collections;using System.Collections.Generic; class CheckDuplicateValues{     //Function that used HashSet to    // find presence of duplicate nodes    public static Boolean checkDupUtil(Node root, HashSet<int> s)    {        // If tree is empty, there are no        // duplicates.        if (root == null)            return false;             // If current node's data is already present.        if (s.Contains(root.data))            return true;             // Insert current node        s.Add(root.data);                 // Recursively check in left and right        // subtrees.        return checkDupUtil(root.left, s) ||                checkDupUtil(root.right, s);    }         // To check if tree has duplicates    public static Boolean checkDup(Node root)    {        HashSet<int> s = new HashSet<int>();        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))            Console.Write("Yes");        else            Console.Write("No");    }} // A binary tree Node has data,// pointer to left child// and a pointer to right childpublic class Node{    public int data;    public Node left, right;    public Node(int data)    {        this.data = data;    }}; // This code is contributed by Arnab Kundu
<script>     // JavaScript Program to check duplicates in Binary Tree         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }     // Function that used HashSet to find    // presence of duplicate nodes    function checkDupUtil(root, s)    {        // If tree is empty, there are no        // duplicates.         if (root == null)            return false;             // If current node's data is already present.        if (s.has(root.data))            return true;             // Insert current node        s.add(root.data);                 // Recursively check in left and right        // subtrees.        return checkDupUtil(root.left, s) ||        checkDupUtil(root.right, s);    }         // To check if tree has duplicates    function checkDup(root)    {        let s = new Set();        return checkDupUtil(root, s);    }         let root = new Node(1);    root.left = new Node(2);    root.right = new Node(2);    root.left.left = new Node(3);    if (checkDup(root))      document.write("Yes");    else      document.write("No");     </script>
Output:  
Yes
 
YouTubeGeeksforGeeks502K subscribersCheck if a Binary Tree (not BST) has duplicate values | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=UdhMwtIcw6w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk
Aditya Sharma 3
Ankit.19
_Gaurav_Tiwari
SHUBHAMSINGH10
andrew1234
decode2207
surinderdawra388
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
Introduction to Tree Data Structure
BFS vs DFS for Binary Tree
Sorted Array to Balanced BST
Expression Tree
Binary Tree (Array implementation)
Deletion in a Binary Tree
Relationship between number of nodes and height of binary tree
Inorder Tree Traversal without recursion and without stack!
How to determine if a binary tree is height-balanced?