Open In App

Find All Duplicate Subtrees

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Traverse the binary tree recursively, starting from the root.
  2. 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.
  3. 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();
}

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.

[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();
}

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.


Next Article
Article Tags :
Practice Tags :

Similar Reads