All Duplicate Subtrees

Last Updated : 24 May, 2026

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]

711

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]

2056957966

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.

Try It Yourself
redirect icon

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>
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
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, ArrayList<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 ArrayList<Node> printAllDups(Node root)
    {
        // Hash map to store count of
        // subtrees.
        Map<String, Integer> map = new HashMap<>();
        ArrayList<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);

        ArrayList<Node> ans = printAllDups(root);

        for (Node node : ans) {
            preOrder(node);
            System.out.println();
        }
    }
}
Python
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)

# Driver Code
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#
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);
    }

    public 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
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// 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 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 preOrder(root)
{
    if (!root)
        return;

    process.stdout.write(root.data + " ");
    preOrder(root.left);
    preOrder(root.right);
}

// Driver Code
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.

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>
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,
                             ArrayList<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 ArrayList<Node> printAllDups(Node root)
    {
        // Hash map to store count of
        // subtrees.
        Map<Integer, Integer> map = new HashMap<>();
        Map<String, Integer> strToInt = new HashMap<>();

        ArrayList<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);

        ArrayList<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)

# Driver Code
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 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 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 preOrder(root)
{
    if (root === null)
        return;

    process.stdout.write(root.data + " ");
    preOrder(root.left);
    preOrder(root.right);
}

// Driver Code
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.

Comment