Check if a Binary Tree contains duplicate subtrees of size 2 or more Last Updated : 07 Nov, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report Try it on GfG Practice Given a Binary Tree, the task is to check whether the Binary tree contains a duplicate sub-tree of size 2 or more. Note: Two same leaf nodes are not considered as the subtree as the size of a leaf node is one.Example:Input: Output: TrueExplanation: Table of Content[Naive Approach] Generating All Subtrees - O(n^2) Time and O(n) Space[Expected Approach] Using Hash Set - O(n) Time and O(n) Space[Naive Approach] Generating All Subtrees - O(n^2) Time and O(n) SpaceThe idea is to generate all subtrees (of size greater than 1) of the binary tree and store their Serialized Form in an array or hash map. Then iterate through the array/map to check for duplicate subtrees. C++ // C++ program to find if there is a duplicate // sub-tree of size 2 or more. #include <bits/stdc++.h> using namespace std; class Node { public: char data; Node *left, *right; Node (char x) { data = x; left = nullptr; right = nullptr; } }; // Function which generates all the subtrees of size>2 // and store its serialized form in map. string dupSubRecur(Node *root, unordered_map<string, int> &map) { // For null nodes, if (root == nullptr) return "N"; // For leaf nodes, return its value in string. if (root->left==nullptr && root->right==nullptr) { return to_string(root->data); } // Process the left and right subtree. string left = dupSubRecur(root->left, map); string right = dupSubRecur(root->right, map); // Generate the serialized form. string curr = ""; curr += to_string(root->data); curr += '*'; curr += left; curr += '*'; curr += right; // Store the subtree in map. map[curr]++; return curr; } int dupSub(Node *root) { unordered_map<string,int> map; // Generate all the subtrees. dupSubRecur(root, map); // Check for all subtrees. for (auto p: map) { // If subtree is duplicate. if (p.second>1) { return 1; } } return 0; } int main() { // A // / \ // B C // / \ \ // D E B // / \ // D E Node* root = new Node('A'); root->left = new Node('B'); root->right = new Node('C'); root->left->left = new Node('D'); root->left->right = new Node('E'); root->right->right = new Node('B'); root->right->right->right = new Node('E'); root->right->right->left = new Node('D'); if (dupSub(root)) { cout << "True" << endl; } else { cout << "False" << endl; } return 0; } Java // Java program to find if there is a duplicate // sub-tree of size 2 or more. import java.util.HashMap; class Node { char data; Node left, right; Node(char x) { data = x; left = null; right = null; } } class GfG { static String dupSubRecur(Node root, HashMap<String, Integer> map) { // For null nodes, if (root == null) return "N"; // For leaf nodes, return its value in string. if (root.left == null && root.right == null) { return String.valueOf(root.data); } // Process the left and right subtree. String left = dupSubRecur(root.left, map); String right = dupSubRecur(root.right, map); // Generate the serialized form. String curr = ""; curr += root.data; curr += '*'; curr += left; curr += '*'; curr += right; // Store the subtree in map. map.put(curr, map.getOrDefault(curr, 0) + 1); return curr; } static int dupSub(Node root) { HashMap<String, Integer> map = new HashMap<>(); // Generate all the subtrees. dupSubRecur(root, map); // Check for all subtrees. for (int val : map.values()) { // If subtree is duplicate. if (val > 1) { return 1; } } return 0; } public static void main(String[] args) { // A // / \ // B C // / \ \ // D E B // / \ // D E Node root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.left = new Node('D'); root.right.right.right = new Node('E'); if (dupSub(root) == 1) { System.out.println("True"); } else { System.out.println("False"); } } } Python # Python program to find if there is a duplicate # sub-tree of size 2 or more. class Node: def __init__(self, x): self.data = x self.left = None self.right = None def dupSubRecur(root, map): # For null nodes, if root is None: return "N" # For leaf nodes, return its value in string. if root.left is None and root.right is None: return str(root.data) # Process the left and right subtree. left = dupSubRecur(root.left, map) right = dupSubRecur(root.right, map) # Generate the serialized form. curr = "" curr += str(root.data) curr += '*' curr += left curr += '*' curr += right # Store the subtree in map. map[curr] = map.get(curr, 0) + 1 return curr def dupSub(root): map = {} # Generate all the subtrees. dupSubRecur(root, map) # Check for all subtrees. for val in map.values(): # If subtree is duplicate. if val > 1: return 1 return 0 if __name__ == "__main__": # A # / \ # B C # / \ \ # D E B # / \ # D E root = Node('A') root.left = Node('B') root.right = Node('C') root.left.left = Node('D') root.left.right = Node('E') root.right.right = Node('B') root.right.right.left = Node('D') root.right.right.right = Node('E') if dupSub(root) == 1: print("True") else: print("False") C# // C# program to find if there is a duplicate // sub-tree of size 2 or more. using System; using System.Collections.Generic; class Node { public char data; public Node left, right; public Node(char x) { data = x; left = null; right = null; } } class GfG { static string dupSubRecur(Node root, Dictionary<string, int> map) { // For null nodes, if (root == null) return "N"; // For leaf nodes, return its value in string. if (root.left == null && root.right == null) { return root.data.ToString(); } // Process the left and right subtree. string left = dupSubRecur(root.left, map); string right = dupSubRecur(root.right, map); // Generate the serialized form. string curr = ""; curr += root.data; curr += '*'; curr += left; curr += '*'; curr += right; // Store the subtree in map. if (map.ContainsKey(curr)) { map[curr]++; } else { map[curr] = 1; } return curr; } static int dupSub(Node root) { Dictionary<string, int> map = new Dictionary<string, int>(); // Generate all the subtrees. dupSubRecur(root, map); // Check for all subtrees. foreach (int val in map.Values) { // If subtree is duplicate. if (val > 1) { return 1; } } return 0; } static void Main() { // A // / \ // B C // / \ \ // D E B // / \ // D E Node root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.left = new Node('D'); root.right.right.right = new Node('E'); if (dupSub(root) == 1) { Console.WriteLine("True"); } else { Console.WriteLine("False"); } } } JavaScript // JavaScript program to find if there is a duplicate // sub-tree of size 2 or more. class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } } function dupSubRecur(root, map) { // For null nodes, if (root === null) return "N"; // For leaf nodes, return its value in string. if (root.left === null && root.right === null) { return root.data.toString(); } // Process the left and right subtree. let left = dupSubRecur(root.left, map); let right = dupSubRecur(root.right, map); // Generate the serialized form. let curr = ""; curr += root.data; curr += '*'; curr += left; curr += '*'; curr += right; // Store the subtree in map. map[curr] = (map[curr] || 0) + 1; return curr; } function dupSub(root) { let map = {}; // Generate all the subtrees. dupSubRecur(root, map); // Check for all subtrees. for (let val of Object.values(map)) { // If subtree is duplicate. if (val > 1) { return 1; } } return 0; } // A // / \ // B C // / \ \ // D E B // / \ // D E let root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.left = new Node('D'); root.right.right.right = new Node('E'); console.log(dupSub(root) === 1 ? "True" : "False"); OutputTrue [Expected Approach] Using Hash Set - O(n) Time and O(n) SpaceThe idea is to use a hash set to store the subtrees in Serialized String Form. For a given subtree of size greater than 1, if its equivalent serialized string already exists, then return true. If all subtrees are unique, return false.Step by step approach:To identify duplicate subtrees efficiently, we only need to check subtrees of size 2 or 3, as any larger duplicate subtree would already contain smaller duplicate subtrees. This reduces the time complexity of concatenating strings to O(1) by focusing only on nodes where both children are either leaf nodes or one is a leaf and the other is null.Use a hash set, say s to track unique subtree structures and an answer variable ans (initially set to false).Define a function dupSubRecur that takes a node and returns a string.If the node is null, return "N".If it's a leaf node, return its value as a string.For internal nodes, first process the left and right subtrees. If either subtree string is empty, return an empty string. Otherwise, concatenate the current node with its left and right subtree strings. If this concatenated string is in the hash set, set ans to true; if not, insert it.Return an empty string for each processed subtree, as upper subtrees don’t need further processing. C++ // C++ program to find if there is a duplicate // sub-tree of size 2 or more. #include <bits/stdc++.h> using namespace std; class Node { public: char data; Node *left, *right; Node (char x) { data = x; left = nullptr; right = nullptr; } }; // Function which checks all the subtree of size 2 or // 3 if they are duplicate. string dupSubRecur(Node *root, unordered_set<string> &s, int &ans) { // For null nodes, if (root == nullptr) return "N"; // For leaf nodes, return its value in string. if (root->left==nullptr && root->right==nullptr) { return to_string(root->data); } string curr = ""; curr += to_string(root->data); // Process the left and right subtree. string left = dupSubRecur(root->left, s, ans); string right = dupSubRecur(root->right, s, ans); // If the node is parent to 2 // leaf nodes, or 1 leaf node and 1 // null node, then concatenate the strings if (left != "" && right != "") { curr += '*'; curr += left; curr += '*'; curr += right; } // Otherwise, there is no need // to process this node. else { return ""; } // If this subtree string is already // present in set, set ans to 1. if (s.find(curr) != s.end()) { ans = 1; } // Else add this string to set. else { s.insert(curr); } return ""; } int dupSub(Node *root) { int ans = 0; unordered_set<string> s; dupSubRecur(root, s, ans); return ans; } int main() { // A // / \ // B C // / \ \ // D E B // / \ // D E Node* root = new Node('A'); root->left = new Node('B'); root->right = new Node('C'); root->left->left = new Node('D'); root->left->right = new Node('E'); root->right->right = new Node('B'); root->right->right->right = new Node('E'); root->right->right->left = new Node('D'); if (dupSub(root)) { cout << "True" << endl; } else { cout << "False" << endl; } return 0; } Java // Java program to find if there is a duplicate // sub-tree of size 2 or more. import java.util.HashSet; class Node { char data; Node left, right; Node(char x) { data = x; left = null; right = null; } } class GfG { // Function which checks all the subtree of size 2 or // 3 if they are duplicate. static String dupSubRecur(Node root, HashSet<String> s, int[] ans) { // For null nodes, if (root == null) return "N"; // For leaf nodes, return its value in string. if (root.left == null && root.right == null) { return String.valueOf(root.data); } String curr = ""; curr += root.data; // Process the left and right subtree. String left = dupSubRecur(root.left, s, ans); String right = dupSubRecur(root.right, s, ans); // If the node is parent to 2 // leaf nodes, or 1 leaf node and 1 // null node, then concatenate the strings if (!left.equals("") && !right.equals("")) { curr += '*' + left + '*' + right; } else { return ""; } // If this subtree string is already // present in set, set ans to 1. if (s.contains(curr)) { ans[0] = 1; } else { s.add(curr); } return ""; } static int dupSub(Node root) { int[] ans = {0}; HashSet<String> s = new HashSet<>(); dupSubRecur(root, s, ans); return ans[0]; } public static void main(String[] args) { // A // / \ // B C // / \ \ // D E B // / \ // D E Node root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.right = new Node('E'); root.right.right.left = new Node('D'); if (dupSub(root) == 1) { System.out.println("True"); } else { System.out.println("False"); } } } Python # Python program to find if there is a duplicate # sub-tree of size 2 or more. class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function which checks all the subtree of size 2 or # 3 if they are duplicate. def dupSubRecur(root, s, ans): # For null nodes, if root is None: return "N" # For leaf nodes, return its value in string. if root.left is None and root.right is None: return str(root.data) curr = str(root.data) # Process the left and right subtree. left = dupSubRecur(root.left, s, ans) right = dupSubRecur(root.right, s, ans) # If the node is parent to 2 # leaf nodes, or 1 leaf node and 1 # null node, then concatenate the strings if left != "" and right != "": curr += '*' + left + '*' + right else: return "" # If this subtree string is already # present in set, set ans to 1. if curr in s: ans[0] = 1 else: s.add(curr) return "" def dupSub(root): ans = [0] s = set() dupSubRecur(root, s, ans) return ans[0] if __name__ == "__main__": # A # / \ # B C # / \ \ # D E B # / \ # D E root = Node('A') root.left = Node('B') root.right = Node('C') root.left.left = Node('D') root.left.right = Node('E') root.right.right = Node('B') root.right.right.right = Node('E') root.right.right.left = Node('D') if dupSub(root): print("True") else: print("False") C# // C# program to find if there is a duplicate // sub-tree of size 2 or more. using System; using System.Collections.Generic; class Node { public char data; public Node left, right; public Node(char x) { data = x; left = null; right = null; } } class GfG { // Function which checks all the subtree of size 2 or // 3 if they are duplicate. static string dupSubRecur(Node root, HashSet<string> s, ref int ans) { // For null nodes, if (root == null) return "N"; // For leaf nodes, return its value in string. if (root.left == null && root.right == null) { return root.data.ToString(); } string curr = root.data.ToString(); // Process the left and right subtree. string left = dupSubRecur(root.left, s, ref ans); string right = dupSubRecur(root.right, s, ref ans); // If the node is parent to 2 // leaf nodes, or 1 leaf node and 1 // null node, then concatenate the strings if (left != "" && right != "") { curr += "*" + left + "*" + right; } else { return ""; } // If this subtree string is already // present in set, set ans to 1. if (s.Contains(curr)) { ans = 1; } else { s.Add(curr); } return ""; } static int dupSub(Node root) { int ans = 0; HashSet<string> s = new HashSet<string>(); dupSubRecur(root, s, ref ans); return ans; } static void Main() { // A // / \ // B C // / \ \ // D E B // / \ // D E Node root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.right = new Node('E'); root.right.right.left = new Node('D'); Console.WriteLine(dupSub(root) == 1 ? "True" : "False"); } } JavaScript // JavaScript program to find if there is a duplicate // sub-tree of size 2 or more. class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } // Function which checks all the subtree of size 2 or // 3 if they are duplicate. function dupSubRecur(root, s, ans) { // For null nodes, if (root === null) return "N"; // For leaf nodes, return its value in string. if (root.left === null && root.right === null) { return root.data.toString(); } let curr = root.data.toString(); // Process the left and right subtree. let left = dupSubRecur(root.left, s, ans); let right = dupSubRecur(root.right, s, ans); // If the node is parent to 2 // leaf nodes, or 1 leaf node and 1 // null node, then concatenate the strings if (left !== "" && right !== "") { curr += '*' + left + '*' + right; } else { return ""; } // If this subtree string is already // present in set, set ans to 1. if (s.has(curr)) { ans[0] = 1; } else { s.add(curr); } return ""; } function dupSub(root) { let ans = [0]; let s = new Set(); dupSubRecur(root, s, ans); return ans[0]; } // A // / \ // B C // / \ \ // D E B // / \ // D E let root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.right = new Node('E'); root.right.right.left = new Node('D'); console.log(dupSub(root) ? "True" : "False"); OutputTrue Comment More infoAdvertise with us Next Article Check if a Binary Tree contains duplicate subtrees of size 2 or more K kartik Improve Article Tags : Tree DSA Google Practice Tags : GoogleTree Similar Reads Binary Tree Data Structure A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and 3 min read Introduction to Binary Tree Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Introduction to Binary TreeRepresentation of Bina 15+ min read Properties of Binary Tree This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levelsBinary tree representationNote: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A bina 4 min read Applications, Advantages and Disadvantages of Binary Tree A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web 2 min read Binary Tree (Array implementation) Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o 6 min read Maximum Depth of Binary Tree Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node.Examples:Input: Output: 2Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which has 11 min read Insertion in a Binary Tree in level order Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner.Examples:Input: key = 12 Output: Explanation: Node with value 12 is inserted into the binary tree at the first position available in level order manner.Approach:The 8 min read Deletion in a Binary Tree Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t 12 min read Enumeration of Binary Trees A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar 3 min read Types of Binary TreeTypes of Binary TreeWe have discussed Introduction to Binary Tree in set 1 and the Properties of Binary Tree in Set 2. In this post, common types of Binary Trees are discussed. Types of Binary Tree based on the number of children:Following are the types of Binary Tree based on the number of children: Full Binary TreeDe 7 min read Complete Binary TreeWe know a tree is a non-linear data structure. It has no limitation on the number of children. A binary tree has a limitation as any node of the tree has at most two children: a left and a right child. What is a Complete Binary Tree?A complete binary tree is a special type of binary tree where all t 7 min read Perfect Binary TreeWhat is a Perfect Binary Tree? A perfect binary tree is a special type of binary tree in which all the leaf nodes are at the same depth, and all non-leaf nodes have two children. In simple terms, this means that all leaf nodes are at the maximum depth of the tree, and the tree is completely filled w 4 min read Like