Given a binary tree, find all duplicate subtrees present in the tree. Two subtrees are considered duplicates if they have the same structure and identical node values at corresponding positions.
Return the root of each such tree in the form of a list.
Example:Â
Input: root = [1, 2, 3, 4, N, 2, 4, N, N, 4]
Output: 2 4 Â 4 Explanation: The tree contains two duplicate subtrees: The subtree rooted at node 4. The subtree rooted at node 2 having left child 4. Therefore, the roots of the duplicate subtrees are 2 and 4.
Input: root = [5, 4, 6, 3, 4, N, N, N, N, 3, 6]
Output: 3 6 Explanation: The binary tree contains two duplicate subtrees: The subtree rooted at node 3 The subtree rooted at node 6 Both of these subtrees appear more than once in the tree with the same structure and node values.
Using Hash Map and Serialization - O(n ^ 2) Time and O(n ^ 2) Space
The idea is to serialize each subtree in the binary tree and use a hash map to keep track of the frequency of each serialized subtree. When a subtree's serialization appears more than once, it indicates a duplicate subtree, and the root node of such duplicate subtree is then added to the result list.
Traverse the binary tree recursively, starting from the root.
Serialize every subtree into a unique string representation.
For each node, combine left subtree, current node, and right subtree strings.
Store the frequency of every serialized subtree in a hash map.
If any subtree serialization appears for the second time, add its root node to the answer list.
Finally, return and print all duplicate subtrees stored in the result.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to serialize all subtrees// of a binary tree.stringserializeTree(Node*root,unordered_map<string,int>&map,vector<Node*>&ans){if(!root)return"N";stringleft=serializeTree(root->left,map,ans);stringright=serializeTree(root->right,map,ans);stringval=to_string(root->data);// Subtree serialization// left - root - rightstringcurr="("+left+")"+val+"("+right+")";map[curr]++;// If such subtree already exists// add root to answerif(map[curr]==2){ans.push_back(root);}returncurr;}// Function to print all duplicate// subtrees of a binary tree.vector<Node*>printAllDups(Node*root){// Hash map to store count of// subtrees.unordered_map<string,int>map;vector<Node*>ans;// Function which will serialize all subtrees// and store duplicate subtrees into answer.serializeTree(root,map,ans);returnans;}voidpreOrder(Node*root){if(root==nullptr)return;cout<<root->data<<" ";preOrder(root->left);preOrder(root->right);}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->right->left=newNode(2);root->right->right=newNode(4);root->right->left->left=newNode(4);vector<Node*>ans=printAllDups(root);for(Node*node:ans){preOrder(node);cout<<endl;}return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to serialize all subtrees// of a binary tree.staticStringserializeTree(Noderoot,Map<String,Integer>map,ArrayList<Node>ans){if(root==null)return"N";Stringleft=serializeTree(root.left,map,ans);Stringright=serializeTree(root.right,map,ans);Stringval=String.valueOf(root.data);// Subtree serialization// left - root - rightStringcurr="("+left+")"+val+"("+right+")";map.put(curr,map.getOrDefault(curr,0)+1);// If such subtree already exists// add root to answerif(map.get(curr)==2){ans.add(root);}returncurr;}// Function to print all duplicate// subtrees of a binary tree.staticArrayList<Node>printAllDups(Noderoot){// Hash map to store count of// subtrees.Map<String,Integer>map=newHashMap<>();ArrayList<Node>ans=newArrayList<>();// Function which will serialize all subtrees// and store duplicate subtrees into answer.serializeTree(root,map,ans);returnans;}staticvoidpreOrder(Noderoot){if(root==null)return;System.out.print(root.data+" ");preOrder(root.left);preOrder(root.right);}publicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.left=newNode(2);root.right.right=newNode(4);root.right.left.left=newNode(4);ArrayList<Node>ans=printAllDups(root);for(Nodenode:ans){preOrder(node);System.out.println();}}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to serialize all subtrees# of a binary tree.defserializeTree(root,map,ans):ifnotroot:return"N"left=serializeTree(root.left,map,ans)right=serializeTree(root.right,map,ans)val=str(root.data)# Subtree serialization# left - root - rightcurr="("+left+")"+val+"("+right+")"map[curr]=map.get(curr,0)+1# If such subtree already exists# add root to answerifmap[curr]==2:ans.append(root)returncurr# Function to print all duplicate# subtrees of a binary tree.defprintAllDups(root):# Hash map to store count of# subtrees.map={}ans=[]# Function which will serialize all subtrees# and store duplicate subtrees into answer.serializeTree(root,map,ans)returnansdefpreOrder(root):ifrootisNone:returnprint(root.data,end=" ")preOrder(root.left)preOrder(root.right)# Driver Codeif__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.right.left=Node(2)root.right.right=Node(4)root.right.left.left=Node(4)ans=printAllDups(root)fornodeinans:preOrder(node)print()
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to serialize all subtrees// of a binary tree.staticstringserializeTree(Noderoot,Dictionary<string,int>map,List<Node>ans){if(root==null)return"N";stringleft=serializeTree(root.left,map,ans);stringright=serializeTree(root.right,map,ans);stringval=root.data.ToString();// Subtree serialization// left - root - rightstringcurr="("+left+")"+val+"("+right+")";if(!map.ContainsKey(curr)){map[curr]=0;}map[curr]++;// If such subtree already exists// add root to answerif(map[curr]==2){ans.Add(root);}returncurr;}// Function to print all duplicate// subtrees of a binary tree.staticList<Node>printAllDups(Noderoot){// Hash map to store count of// subtrees.Dictionary<string,int>map=newDictionary<string,int>();List<Node>ans=newList<Node>();// Function which will serialize all subtrees// and store duplicate subtrees into answer.serializeTree(root,map,ans);returnans;}staticvoidpreOrder(Noderoot){if(root==null)return;Console.Write(root.data+" ");preOrder(root.left);preOrder(root.right);}publicstaticvoidMain(){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.left=newNode(2);root.right.right=newNode(4);root.right.left.left=newNode(4);List<Node>ans=printAllDups(root);foreach(Nodenodeinans){preOrder(node);Console.WriteLine();}}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to print all duplicate// subtrees of a binary tree.functionprintAllDups(root){// Hash map to store count of// subtrees.letmap=newMap();letans=[];// Function which will serialize all subtrees// and store duplicate subtrees into answer.serializeTree(root,map,ans);returnans;}// Function to serialize all subtrees// of a binary tree.functionserializeTree(root,map,ans){if(!root)return"N";letleft=serializeTree(root.left,map,ans);letright=serializeTree(root.right,map,ans);letval=root.data.toString();// Subtree serialization// left - root - rightletcurr="("+left+")"+val+"("+right+")";map.set(curr,(map.get(curr)||0)+1);// If such subtree already exists// add root to answerif(map.get(curr)===2){ans.push(root);}returncurr;}functionpreOrder(root){if(!root)return;process.stdout.write(root.data+" ");preOrder(root.left);preOrder(root.right);}// Driver Codeletroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.left=newNode(2);root.right.right=newNode(4);root.right.left.left=newNode(4);letans=printAllDups(root);for(letnodeofans){preOrder(node);console.log();}
Output
4
2 4
Time Complexity: O(n^2) Â Since string copying takes O(n) extra time. Auxiliary Space: O(n^2) Since we are hashing a string for each node and length of this string can be of the order N.
Using Hash Map and Integer IDs - O(n) Time and O(n) Space
The idea of this approach is to avoid the time-consuming process of concatenating strings for subtree serialization by assigning a unique integer ID to each serialized subtree.
So the key that we use to do look up in hash table for duplicate subtrees becomes of constant length. Why? because it is combination of three integers (left subtree ID, root value and right subtree ID) separated by some constant number of separator characters.
We now mainly use two maps, one to store subtree and id mapping (with fixed length key explained above and a an integer id value), and other map with (ID as key and count as value). Whenever the count becomes 2, we add the subtree to result.
Traverse the binary tree recursively, starting from the root node.
Serialize each subtree using left subtree ID, current node value, and right subtree ID.
Use a hash map to assign a unique integer ID to every unique subtree serialization.
Store the frequency of each subtree ID in another hash map.
If any subtree ID appears for the second time, add its root node to the answer list.
Finally, return and print all duplicate subtrees stored in the result.
C++
// C++ program to find all Duplicate Subtrees#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to serialize all subtrees// of a binary tree.intserializeTree(Node*root,unordered_map<int,int>&map,unordered_map<string,int>&strToInt,vector<Node*>&ans,int&idNum){if(!root)return0;intleft=serializeTree(root->left,map,strToInt,ans,idNum);intright=serializeTree(root->right,map,strToInt,ans,idNum);stringval=to_string(root->data);// Subtree serialization// left - root - rightstringcurr="("+to_string(left)+")"+val+"("+to_string(right)+")";// Assign an integer id for the serialized string.intcurrId;// If id already existsif(strToInt.find(curr)!=strToInt.end()){currId=strToInt[curr];}// Else assign a new id.else{currId=idNum++;strToInt[curr]=currId;}map[currId]++;// If such subtree already exists// add root to answerif(map[currId]==2){ans.push_back(root);}returncurrId;}// Function to print all duplicate// subtrees of a binary tree.vector<Node*>printAllDups(Node*root){// Hash map to store count of// subtrees.unordered_map<int,int>map;unordered_map<string,int>strToInt;vector<Node*>ans;// Variable to assign unique integer id// for each serialized string.intidNum=1;// Function which will serialize all subtrees// and store duplicate subtrees into answer.serializeTree(root,map,strToInt,ans,idNum);returnans;}voidpreOrder(Node*root){if(root==nullptr)return;cout<<root->data<<" ";preOrder(root->left);preOrder(root->right);}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->right->left=newNode(2);root->right->right=newNode(4);root->right->left->left=newNode(4);vector<Node*>ans=printAllDups(root);for(Node*node:ans){preOrder(node);cout<<endl;}return0;}
Java
// Java program to find all Duplicate Subtreesimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to serialize all subtrees// of a binary tree.staticintserializeTree(Noderoot,Map<Integer,Integer>map,Map<String,Integer>strToInt,ArrayList<Node>ans,int[]idNum){if(root==null)return0;intleft=serializeTree(root.left,map,strToInt,ans,idNum);intright=serializeTree(root.right,map,strToInt,ans,idNum);Stringval=Integer.toString(root.data);// Subtree serialization// left - root - rightStringcurr="("+left+")"+val+"("+right+")";// Assign an integer id for the serialized string.intcurrId;// If id already existsif(strToInt.containsKey(curr)){currId=strToInt.get(curr);}// Else assign a new id.else{currId=idNum[0]++;strToInt.put(curr,currId);}map.put(currId,map.getOrDefault(currId,0)+1);// If such subtree already exists// add root to answerif(map.get(currId)==2){ans.add(root);}returncurrId;}// Function to print all duplicate// subtrees of a binary tree.staticArrayList<Node>printAllDups(Noderoot){// Hash map to store count of// subtrees.Map<Integer,Integer>map=newHashMap<>();Map<String,Integer>strToInt=newHashMap<>();ArrayList<Node>ans=newArrayList<>();// Variable to assign unique integer id// for each serialized string.int[]idNum={1};// Function which will serialize all subtrees// and store duplicate subtrees into answer.serializeTree(root,map,strToInt,ans,idNum);returnans;}staticvoidpreOrder(Noderoot){if(root==null)return;System.out.print(root.data+" ");preOrder(root.left);preOrder(root.right);}publicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.left=newNode(2);root.right.right=newNode(4);root.right.left.left=newNode(4);ArrayList<Node>ans=printAllDups(root);for(Nodenode:ans){preOrder(node);System.out.println();}}}
Python
# Python program to find all Duplicate SubtreesclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to serialize all subtrees# of a binary tree.defserializeTree(root,nodeCount,strToInt,ans,idNum):ifnotroot:return0left=serializeTree(root.left,nodeCount,strToInt,ans,idNum)right=serializeTree(root.right,nodeCount,strToInt,ans,idNum)val=str(root.data)# Subtree serialization# left - root - rightcurr=f"({left}){val}({right})"# Assign an integer id for the serialized string.ifcurrinstrToInt:currId=strToInt[curr]else:currId=idNum[0]idNum[0]+=1strToInt[curr]=currIdnodeCount[currId]=nodeCount.get(currId,0)+1# If such subtree already exists# add root to answerifnodeCount[currId]==2:ans.append(root)returncurrId# Function to print all duplicate# subtrees of a binary tree.defprintAllDups(root):# Hash map to store count of# subtrees.nodeCount={}strToInt={}ans=[]# Variable to assign unique integer id# for each serialized string.idNum=[1]# Function which will serialize all subtrees# and store duplicate subtrees into answer.serializeTree(root,nodeCount,strToInt,ans,idNum)returnansdefpreOrder(root):ifrootisNone:returnprint(root.data,end=" ")preOrder(root.left)preOrder(root.right)# Driver Codeif__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.right.left=Node(2)root.right.right=Node(4)root.right.left.left=Node(4)ans=printAllDups(root)fornodeinans:preOrder(node)print()
C#
// C# program to find all Duplicate SubtreesusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to serialize all subtrees// of a binary tree.staticintserializeTree(Noderoot,Dictionary<int,int>map,Dictionary<string,int>strToInt,List<Node>ans,refintidNum){if(root==null)return0;intleft=serializeTree(root.left,map,strToInt,ans,refidNum);intright=serializeTree(root.right,map,strToInt,ans,refidNum);stringval=root.data.ToString();// Subtree serialization// left - root - rightstringcurr="("+left+")"+val+"("+right+")";// Assign an integer id for the serialized string.intcurrId;// If id already existsif(strToInt.ContainsKey(curr)){currId=strToInt[curr];}// Else assign a new id.else{currId=idNum++;strToInt[curr]=currId;}if(!map.ContainsKey(currId))map[currId]=0;map[currId]++;// If such subtree already exists// add root to answerif(map[currId]==2){ans.Add(root);}returncurrId;}// Function to print all duplicate// subtrees of a binary tree.staticList<Node>printAllDups(Noderoot){// Hash map to store count of// subtrees.Dictionary<int,int>map=newDictionary<int,int>();Dictionary<string,int>strToInt=newDictionary<string,int>();List<Node>ans=newList<Node>();// Variable to assign unique integer id// for each serialized string.intidNum=1;// Function which will serialize all subtrees// and store duplicate subtrees into answer.serializeTree(root,map,strToInt,ans,refidNum);returnans;}staticvoidpreOrder(Noderoot){if(root==null)return;Console.Write(root.data+" ");preOrder(root.left);preOrder(root.right);}staticvoidMain(){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.left=newNode(2);root.right.right=newNode(4);root.right.left.left=newNode(4);List<Node>ans=printAllDups(root);foreach(Nodenodeinans){preOrder(node);Console.WriteLine();}}}
JavaScript
// JavaScript program to find all Duplicate SubtreesclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to print all duplicate// subtrees of a binary tree.functionprintAllDups(root){// Hash map to store count of// subtrees.letmap=newMap();letstrToInt=newMap();letans=[];// Variable to assign unique integer id// for each serialized string.letidNum={value:1};// Function which will serialize all subtrees// and store duplicate subtrees into answer.serializeTree(root,map,strToInt,ans,idNum);returnans;}// Function to serialize all subtrees// of a binary tree.functionserializeTree(root,map,strToInt,ans,idNum){if(!root)return0;letleft=serializeTree(root.left,map,strToInt,ans,idNum);letright=serializeTree(root.right,map,strToInt,ans,idNum);letval=root.data.toString();// Subtree serialization// left - root - rightletcurr=`(${left})${val}(${right})`;// Assign an integer id for the serialized string.letcurrId;// If id already existsif(strToInt.has(curr)){currId=strToInt.get(curr);}// Else assign a new id.else{currId=idNum.value++;strToInt.set(curr,currId);}map.set(currId,(map.get(currId)||0)+1);// If such subtree already exists// add root to answerif(map.get(currId)===2){ans.push(root);}returncurrId;}functionpreOrder(root){if(root===null)return;process.stdout.write(root.data+" ");preOrder(root.left);preOrder(root.right);}// Driver Codeletroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.left=newNode(2);root.right.right=newNode(4);root.right.left.left=newNode(4);letans=printAllDups(root);for(letnodeofans){preOrder(node);console.log();}
Output
4
2 4
Time Complexity: O(n) as each node is traversed only once and the string concatenation only involves three integers. Auxiliary Space: O(n) due to hash map.