15% off all plans & roadmaps Use code

See plans

Find Duplicate Subtrees

Updated

TL;DR: Find every subtree shape that appears more than once in a binary tree, and return one root for each repeated shape. Give each subtree an integer ID built from its value and its children's IDs, then count the IDs in one pass.

Problem

Given the root of a binary tree, return all duplicate subtrees.

For each kind of duplicate subtree, return the root node of any one of them.

Two trees are duplicates when they have the same structure and the same node values.

Example 1

Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]

Example 2

Input: root = [2,1,1]
Output: [[1]]

Example 3

Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]

Constraints

  • The number of nodes in the tree is in the range [1, 5000].
  • -200 <= Node.val <= 200

Constraints that matter

  • With n up to 5000, comparing every pair of subtrees directly costs O(n^3) in the worst case, so the solution needs shared work between subtrees.
  • Each subtree must be identified by its value and both children, including missing children. Otherwise a left-only 4 and a right-only 4 would look the same.
  • A chain can be 5000 levels deep, and Python's default recursion limit is about 1000, so the traversal should use an explicit stack.
  • Only one root per duplicate class is returned, so the output is at most n nodes and the counting must notice the second occurrence exactly once.

View on LeetCode

Hints

Hint 1

Two subtrees match when their roots hold the same value and their left subtrees match and their right subtrees match.

Hint 2

Treat every node as a candidate root.

Solution

Intuition

Two subtrees match when their roots hold the same value and their left subtrees match and their right subtrees match. That definition refers to smaller subtrees, so you can build a label from the bottom up. Give each distinct subtree shape an integer ID, and let a parent's ID depend only on its value and its two children's IDs.

Picture a parts catalog where each assembly gets a number built from its own label and the numbers of its two sub-assemblies. The hash map is the catalog, the triple is the part description, and a repeated number means an identical assembly was already built.

The null side needs its own label. A node with only a left child 4 and a node with only a right child 4 must get different IDs. Use 0 for a missing child and start real IDs at 1. The triple (value, left ID, right ID) then identifies a shape exactly.

Count how often each ID appears while you go. The second time an ID shows up, that node is the root of a repeated shape, so you report it once. This is the serialization idea without building long strings. Each node does a fixed amount of hash work, so the whole tree is handled in linear time.

Watch the pattern animation

Worked example

Input: root = [1, 2, 3, 4, null, 2, 4, null, null, 4]
Output: [[4], [2, 4]]
Explanation: The value 4 appears as a leaf three times, and the subtree is reported once. The two nodes with value 2 each have a left child 4 and no right child, so one of them is reported. Any order is accepted, and this order matches the verified output.

Approach 1: Brute force: compare every pair of subtrees

Treat every node as a candidate root. Compare its subtree with the subtree of every other node by walking both trees together. A node joins the result only when its class has no representative yet, so each repeated shape is reported once.

What is slow: the same pairs of subtrees are compared again and again, and each comparison can walk up to n nodes. With n nodes, you test n times n pairs, and each test may cost n steps. The comparison work is repeated, and nothing is remembered between tests.

Steps

  1. Collect every node of the tree into a list. Any order works.
  2. For each node a in the list, skip it if an earlier result root has the same subtree as a.
  3. Otherwise, search the list for another node b (with b not equal to a) whose subtree matches a.
  4. If such a b exists, add a to the result.
  5. To compare two subtrees, push the pair of roots on a stack. Pop a pair, fail on a shape or value mismatch, and push both children pairs.

Dry run

Label the nodes for the trace. 1 is the root, A the left 2, B the 4 under A, C the 3 on the right, D the 2 under C, E the 4 under D, and F the 4 under C.

The node list in preorder is 1, A, B, C, D, E, F.

  • Node 1 has no matching subtree, so it is not added.
  • Node A matches D, so A goes into the result. Result: [A].
  • Node B matches E, so B goes into the result. Result: [A, B].
  • Node C has no match.
  • Node D matches A, which already represents its class, so it is skipped.
  • Nodes E and F match B, so both are skipped.

The result is [A, B], which is [[2, 4], [4]]. That is a valid answer, and the problem accepts any order.

Complexity

TimeO(n^3)
SpaceO(n)

Let n be the number of nodes. The outer loop visits n nodes, and the inner loop tests up to n others, so the pair count is n * n. A single comparison stops at the first mismatch but can visit up to n node pairs, so it costs O(n) in the worst case, giving O(n^3) overall. The node list, the comparison stack and the result each hold at most n entries, so the space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
        def collect(start):
            nodes = []
            stack = [start] if start else []
            while stack:
                node = stack.pop()
                nodes.append(node)
                if node.right:
                    stack.append(node.right)
                if node.left:
                    stack.append(node.left)
            return nodes

        def same(a, b):
            # Walk both trees together and stop at the first mismatch
            stack = [(a, b)]
            while stack:
                x, y = stack.pop()
                if x is None and y is None:
                    continue
                if x is None or y is None or x.val != y.val:
                    return False
                stack.append((x.left, y.left))
                stack.append((x.right, y.right))
            return True

        nodes = collect(root)
        result = []
        for i, a in enumerate(nodes):
            if any(same(a, r) for r in result):
                continue
            for j, b in enumerate(nodes):
                if i != j and same(a, b):
                    result.append(a)
                    break
        return result

The Serialization and Deserialization infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Serialization and Deserialization

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: One-pass hash map of canonical IDsOptimalSerialization and Deserialization

The brute force repeats comparisons, so each subtree's shape should be computed once. Give every shape an integer ID. A node's ID depends only on its value and its children's IDs, so a parent can be labeled right after its children.

What is slow: each comparison walks a whole subtree again. The insight that fixes it: two subtrees with the same (value, left ID, right ID) triple are equal, because their children were already shown equal by their IDs. A hash map from triples to IDs turns each comparison into one lookup, and a count per ID finds the repeats.

Steps

  1. Walk the tree from the root with a stack, recording each node in a list. A parent is recorded before its children.
  2. Process the list in reverse, so every child is handled before its parent.
  3. For each node, read the IDs of its left and right child, using 0 when the child is missing.
  4. Form the key (value, left ID, right ID). If the key is new, give it the next ID, which is the table size plus 1.
  5. Store the node's ID, and add one to that ID's count.
  6. When a count becomes exactly 2, add the node to the result. Return the result.

Dry run

The walk order is 1, C, F, D, E, A, B, so the reversed list is B, A, E, D, F, C, 1.

StepNodeLeft IDRight IDKeyIDCountResult
1B (4)00(4,0,0) new11[]
2A (2)10(2,1,0) new21[]
3E (4)00(4,0,0)12[E]
4D (2)10(2,1,0)22[E, D]
5F (4)00(4,0,0)13[E, D]
6C (3)21(3,2,1) new31[E, D]
7123(1,2,3) new41[E, D]

The result is [E, D], which is [[4], [2, 4]]. That matches the verified output.

Complexity

TimeO(n)
SpaceO(n)

Let n be the number of nodes. The stack walk pushes and pops each node once, and the reversed pass handles each node once. Each node does a fixed number of map operations on a triple of integers, so the work per node is constant on average. The node list, the stack, the node-to-ID map and the key table each hold at most n entries, so the space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
        result = []
        if root is None:
            return result
        # Walk the tree with a stack, recording each node before its children
        order = []
        stack = [root]
        while stack:
            node = stack.pop()
            order.append(node)
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        table = {}      # (val, left_id, right_id) -> shape id
        node_id = {}    # node -> shape id of its subtree
        count = {}      # shape id -> times seen
        # Reversed, every child is handled before its parent
        for node in reversed(order):
            left_id = node_id[node.left] if node.left else 0
            right_id = node_id[node.right] if node.right else 0
            key = (node.val, left_id, right_id)
            if key not in table:
                table[key] = len(table) + 1
            shape = table[key]
            node_id[node] = shape
            count[shape] = count.get(shape, 0) + 1
            if count[shape] == 2:
                result.append(node)
        return result

Common mistakes

  • Using if count[shape] > 1 where == 2 belongs. A subtree that appears three times is added twice. Add the node only on the transition to 2.
  • Giving the first real subtree ID 0. A missing child also reads as 0, so a real subtree and a null child collide. Start real IDs at 1 and use 0 for null.
  • Keying on the value alone, or dropping the child IDs. A node with only a left child 4 and a node with only a right child 4 would collide. Always key on both child IDs, with 0 for a missing child.
  • Processing the stack list in its original order. A parent may be looked up before its children have IDs, so node_id[node.left] fails. Reverse the list first.
  • Writing the serialization recursively in Python. A 5000-node chain exceeds the default recursion limit of about 1000 and raises RecursionError. Use the explicit stack shown in the code.

Edge cases

  • A single node, such as [1]. No subtree repeats, so the answer is an empty list.
  • [2,1,1]. The two leaves with value 1 share one shape, so the answer is [[1]] with one of the leaves.
  • A left-only 4 under one parent and a right-only 4 under another. The null markers keep them apart, so they are not duplicates.
  • Three leaves with value 4, as in Example 1. The shape is reported once, not twice.
  • A chain of 5000 nodes that all hold the value 1. Every subtree has a different size, so the answer is an empty list, and the walk must not overflow the stack.
  • [-1,-1,-1]. The key uses the signed value directly, so the answer is [[-1]].

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Find Duplicate Subtrees, with how to answer them.

Unlock the follow-ups

Find Duplicate Subtrees FAQ

What is the time complexity of Find Duplicate Subtrees?

The optimal hash map solution runs in O(n) time, where n is the number of nodes, because each node does constant work on average. The brute force pair check runs in O(n^3) in the worst case. Both approaches use O(n) space.

Why use a hash map for Find Duplicate Subtrees?

A hash map counts how many times each shape ID appears in constant average time. The ID key replaces a full subtree comparison with a single lookup. Without the map, you would need to compare each subtree against every other one.

Can Find Duplicate Subtrees be solved in O(1) extra space?

No, not with the methods shown here. The shape map holds one entry per distinct shape, which can reach n, and the traversal stack reaches n on a skewed tree. O(n) is the honest bound.

Does the order of the returned roots matter?

No. The problem accepts any order and any one root per duplicate class. The optimal code returns the order shown in the verified example.

Why does the Python solution avoid recursion?

Python's default recursion limit is about 1000, and a skewed tree can reach 5000 levels. The explicit stack avoids RecursionError without changing the algorithm. The same iterative form works in all six languages without tuning the stack size.

Asked at

See which companies ask this — Pro

Practise it