Find All Duplicate Subtrees
Last Updated :
21 Mar, 2025
Given a binary tree, the task is to find all duplicate subtrees. For each duplicate subtree, we only need to return the root node of any one of them. Two trees are duplicates if they have the same structure with the same node values.
Example:
Input : Binary tree
1
/ \
2 3
/ / \
4 2 4
/
4
Output :
2
/ and 4
4
Explanation: The above subtrees are present twice in the binary tree.
[Naive Approach] Using Hash Map and Serialization - O(n^2) Time and 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 of that subtree is added to the result.
Step by step approach:
- Traverse the binary tree recursively, starting from the root.
- For each node,
- If it is
NULL
, return "N" to represent a null node. - Recursively serialize the left and right subtrees of the current node.
- Combine the serialized left subtree, the current node's value, and the serialized right subtree into a single string in the format "(left) value (right)".
- Use a hash map to count how many times each serialized subtree string appears.
- If a serialized subtree string appears exactly twice ( to avoid adding same duplicate subtree into result), add the current node (root of the subtree) to the result list.
- Return the serialized string for further processing in the recursion.
- After traversing the entire tree, the result list will contain the roots of all duplicate subtrees.
C++
// C++ program to find all Duplicate Subtrees
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node (int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// Function to serialize all subtrees
// of a binary tree.
string serializeTree(Node* root, unordered_map<string, int> &map,
vector<Node*> &ans) {
if (!root) return "N";
string left = serializeTree(root->left, map, ans);
string right = serializeTree(root->right, map, ans);
string val = to_string(root->data);
// Subtree serialization
// left - root - right
string curr = "(" + left + ")" + val + "(" + right + ")";
map[curr]++;
// If such subtree already exists
// add root to answer
if (map[curr] == 2) {
ans.push_back(root);
}
return curr;
}
// 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);
return ans;
}
void preOrder(Node* root) {
if (root == nullptr) return;
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(2);
root->right->right = new Node(4);
root->right->left->left = new Node(4);
vector<Node*> ans = printAllDups(root);
for (Node* node: ans) {
preOrder(node);
cout << endl;
}
return 0;
}
Java
// Java program to find all Duplicate Subtrees
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to serialize all subtrees
// of a binary tree.
static String serializeTree(Node root, Map<String, Integer> map,
List<Node> ans) {
if (root == null) return "N";
String left = serializeTree(root.left, map, ans);
String right = serializeTree(root.right, map, ans);
String val = String.valueOf(root.data);
// Subtree serialization
// left - root - right
String curr = "(" + left + ")" + val + "(" + right + ")";
map.put(curr, map.getOrDefault(curr, 0) + 1);
// If such subtree already exists
// add root to answer
if (map.get(curr) == 2) {
ans.add(root);
}
return curr;
}
// Function to print all duplicate
// subtrees of a binary tree.
static List<Node> printAllDups(Node root) {
// Hash map to store count of
// subtrees.
Map<String, Integer> map = new HashMap<>();
List<Node> ans = new ArrayList<>();
// Function which will serialize all subtrees
// and store duplicate subtrees into answer.
serializeTree(root, map, ans);
return ans;
}
static void preOrder(Node root) {
if (root == null) return;
System.out.print(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(2);
root.right.right = new Node(4);
root.right.left.left = new Node(4);
List<Node> ans = printAllDups(root);
for (Node node : ans) {
preOrder(node);
System.out.println();
}
}
}
Python
# Python program to find all Duplicate Subtrees
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to serialize all subtrees
# of a binary tree.
def serializeTree(root, map, ans):
if not root:
return "N"
left = serializeTree(root.left, map, ans)
right = serializeTree(root.right, map, ans)
val = str(root.data)
# Subtree serialization
# left - root - right
curr = "(" + left + ")" + val + "(" + right + ")"
map[curr] = map.get(curr, 0) + 1
# If such subtree already exists
# add root to answer
if map[curr] == 2:
ans.append(root)
return curr
# Function to print all duplicate
# subtrees of a binary tree.
def printAllDups(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)
return ans
def preOrder(root):
if root is None:
return
print(root.data, end=" ")
preOrder(root.left)
preOrder(root.right)
if __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)
for node in ans:
preOrder(node)
print()
C#
// C# program to find all Duplicate Subtrees
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to serialize all subtrees
// of a binary tree.
static string serializeTree(Node root, Dictionary<string, int> map,
List<Node> ans) {
if (root == null) return "N";
string left = serializeTree(root.left, map, ans);
string right = serializeTree(root.right, map, ans);
string val = root.data.ToString();
// Subtree serialization
// left - root - right
string curr = "(" + left + ")" + val + "(" + right + ")";
if (!map.ContainsKey(curr)) {
map[curr] = 0;
}
map[curr]++;
// If such subtree already exists
// add root to answer
if (map[curr] == 2) {
ans.Add(root);
}
return curr;
}
// Function to print all duplicate
// subtrees of a binary tree.
static List<Node> printAllDups(Node root) {
// Hash map to store count of
// subtrees.
Dictionary<string, int> map = new Dictionary<string, int>();
List<Node> ans = new List<Node>();
// Function which will serialize all subtrees
// and store duplicate subtrees into answer.
serializeTree(root, map, ans);
return ans;
}
static void preOrder(Node root) {
if (root == null) return;
Console.Write(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
static void Main() {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(2);
root.right.right = new Node(4);
root.right.left.left = new Node(4);
List<Node> ans = printAllDups(root);
foreach (Node node in ans) {
preOrder(node);
Console.WriteLine();
}
}
}
JavaScript
// JavaScript program to find all Duplicate Subtrees
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Function to serialize all subtrees
// of a binary tree.
function serializeTree(root, map, ans) {
if (!root) return "N";
let left = serializeTree(root.left, map, ans);
let right = serializeTree(root.right, map, ans);
let val = root.data.toString();
// Subtree serialization
// left - root - right
let curr = "(" + left + ")" + val + "(" + right + ")";
map.set(curr, (map.get(curr) || 0) + 1);
// If such subtree already exists
// add root to answer
if (map.get(curr) === 2) {
ans.push(root);
}
return curr;
}
// Function to print all duplicate
// subtrees of a binary tree.
function printAllDups(root) {
// Hash map to store count of
// subtrees.
let map = new Map();
let ans = [];
// Function which will serialize all subtrees
// and store duplicate subtrees into answer.
serializeTree(root, map, ans);
return ans;
}
function preOrder(root) {
if (!root) return;
process.stdout.write(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(2);
root.right.right = new Node(4);
root.right.left.left = new Node(4);
let ans = printAllDups(root);
for (let node of ans) {
preOrder(node);
console.log();
}
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.
[Expected Approach] Using Hash Map and Integer IDs - O(n) Time and 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.
C++
// C++ program to find all Duplicate Subtrees
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node (int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// Function to serialize all subtrees
// of a binary tree.
int serializeTree(Node* root, unordered_map<int, int> &map,
unordered_map<string,int> &strToInt, vector<Node*> &ans, int &idNum) {
if (!root) return 0;
int left = serializeTree(root->left, map, strToInt, ans, idNum);
int right = serializeTree(root->right, map, strToInt, ans, idNum);
string val = to_string(root->data);
// Subtree serialization
// left - root - right
string curr = "(" + to_string(left) + ")" +
val + "(" + to_string(right) + ")";
// Assign an integer id for the serialized string.
int currId;
// If id already exists
if (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 answer
if (map[currId] == 2) {
ans.push_back(root);
}
return currId;
}
// 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.
int idNum = 1;
// Function which will serialize all subtrees
// and store duplicate subtrees into answer.
serializeTree(root, map, strToInt, ans, idNum);
return ans;
}
void preOrder(Node* root) {
if (root == nullptr) return;
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(2);
root->right->right = new Node(4);
root->right->left->left = new Node(4);
vector<Node*> ans = printAllDups(root);
for (Node* node: ans) {
preOrder(node);
cout << endl;
}
return 0;
}
Java
// Java program to find all Duplicate Subtrees
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to serialize all subtrees
// of a binary tree.
static int serializeTree(Node root, Map<Integer, Integer> map,
Map<String, Integer> strToInt, List<Node> ans, int[] idNum) {
if (root == null) return 0;
int left = serializeTree(root.left, map, strToInt, ans, idNum);
int right = serializeTree(root.right, map, strToInt, ans, idNum);
String val = Integer.toString(root.data);
// Subtree serialization
// left - root - right
String curr = "(" + left + ")" + val + "(" + right + ")";
// Assign an integer id for the serialized string.
int currId;
// If id already exists
if (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 answer
if (map.get(currId) == 2) {
ans.add(root);
}
return currId;
}
// Function to print all duplicate
// subtrees of a binary tree.
static List<Node> printAllDups(Node root) {
// Hash map to store count of
// subtrees.
Map<Integer, Integer> map = new HashMap<>();
Map<String, Integer> strToInt = new HashMap<>();
List<Node> ans = new ArrayList<>();
// 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);
return ans;
}
static void preOrder(Node root) {
if (root == null) return;
System.out.print(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(2);
root.right.right = new Node(4);
root.right.left.left = new Node(4);
List<Node> ans = printAllDups(root);
for (Node node : ans) {
preOrder(node);
System.out.println();
}
}
}
Python
# Python program to find all Duplicate Subtrees
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to serialize all subtrees
# of a binary tree.
def serializeTree(root, nodeCount, strToInt, ans, idNum):
if not root:
return 0
left = serializeTree(root.left, nodeCount, strToInt, ans, idNum)
right = serializeTree(root.right, nodeCount, strToInt, ans, idNum)
val = str(root.data)
# Subtree serialization
# left - root - right
curr = f"({left}){val}({right})"
# Assign an integer id for the serialized string.
if curr in strToInt:
currId = strToInt[curr]
else:
currId = idNum[0]
idNum[0] += 1
strToInt[curr] = currId
nodeCount[currId] = nodeCount.get(currId, 0) + 1
# If such subtree already exists
# add root to answer
if nodeCount[currId] == 2:
ans.append(root)
return currId
# Function to print all duplicate
# subtrees of a binary tree.
def printAllDups(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)
return ans
def preOrder(root):
if root is None:
return
print(root.data, end=" ")
preOrder(root.left)
preOrder(root.right)
if __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)
for node in ans:
preOrder(node)
print()
C#
// C# program to find all Duplicate Subtrees
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to serialize all subtrees
// of a binary tree.
static int serializeTree(Node root, Dictionary<int, int> map,
Dictionary<string, int> strToInt, List<Node> ans, ref int idNum) {
if (root == null) return 0;
int left = serializeTree(root.left, map, strToInt, ans, ref idNum);
int right = serializeTree(root.right, map, strToInt, ans, ref idNum);
string val = root.data.ToString();
// Subtree serialization
// left - root - right
string curr = "(" + left + ")" + val + "(" + right + ")";
// Assign an integer id for the serialized string.
int currId;
// If id already exists
if (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 answer
if (map[currId] == 2) {
ans.Add(root);
}
return currId;
}
// Function to print all duplicate
// subtrees of a binary tree.
static List<Node> printAllDups(Node root) {
// Hash map to store count of
// subtrees.
Dictionary<int, int> map = new Dictionary<int, int>();
Dictionary<string, int> strToInt = new Dictionary<string, int>();
List<Node> ans = new List<Node>();
// 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, ref idNum);
return ans;
}
static void preOrder(Node root) {
if (root == null) return;
Console.Write(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
static void Main() {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(2);
root.right.right = new Node(4);
root.right.left.left = new Node(4);
List<Node> ans = printAllDups(root);
foreach (Node node in ans) {
preOrder(node);
Console.WriteLine();
}
}
}
JavaScript
// JavaScript program to find all Duplicate Subtrees
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Function to serialize all subtrees
// of a binary tree.
function serializeTree(root, map, strToInt, ans, idNum) {
if (!root) return 0;
let left = serializeTree(root.left, map, strToInt, ans, idNum);
let right = serializeTree(root.right, map, strToInt, ans, idNum);
let val = root.data.toString();
// Subtree serialization
// left - root - right
let curr = `(${left})${val}(${right})`;
// Assign an integer id for the serialized string.
let currId;
// If id already exists
if (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 answer
if (map.get(currId) === 2) {
ans.push(root);
}
return currId;
}
// Function to print all duplicate
// subtrees of a binary tree.
function printAllDups(root) {
// Hash map to store count of
// subtrees.
let map = new Map();
let strToInt = new Map();
let ans = [];
// Variable to assign unique integer id
// for each serialized string.
let idNum = { value: 1 };
// Function which will serialize all subtrees
// and store duplicate subtrees into answer.
serializeTree(root, map, strToInt, ans, idNum);
return ans;
}
function preOrder(root) {
if (root === null) return;
process.stdout.write(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(2);
root.right.right = new Node(4);
root.right.left.left = new Node(4);
let ans = printAllDups(root);
for (let node of ans) {
preOrder(node);
console.log();
}
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem