Find Duplicate Subtrees solution explained

To find duplicate subtrees, walk the tree in post-order and give every subtree a compact key built from its left child's key, its value and its right child's key; the first time a key is seen a second time, add that node to the answer. Turning each (left id, value, right id) triple into a small integer id keeps the keys short, so the whole pass is O(n) expected time and O(n) space.

By Published 9 min read

What is being asked

Given the root of a binary tree, find every subtree that appears more than once. Two subtrees count as the same when they have the same structure and the same value at every matching position, including where children are missing. For each group of identical subtrees, return just one of their root nodes, and return each group only once no matter how many copies it has. The order of the answer usually does not matter.

           1
         /   \
        4     3
       /     / \
      2     4   2
           /
          2

Leaf 2 appears three times        -> report one leaf 2
4 with a left child 2 appears twice -> report one of those 4 nodes
Answer: [leaf 2, the subtree 4 -> 2] in any order
A tree drawn for this page

Shape matters as much as values. A node 5 with a left child 6 and a node 5 with a right child 6 are different subtrees, even though they hold the same numbers. And a group with three copies is reported once, not twice. Those two rules are where most wrong answers come from.

What the interviewer is checking

The problem is about turning a structure into something you can hash. Interviewers want to see that you build the description from the children upward, that your description is unambiguous, and that you know what it costs. Strong candidates usually reach the string-key solution, and the best ones notice that the strings themselves can be long and offer the integer-id refinement. Follow-ups tend to be:

  • Why include null markers? Without them, different shapes can produce the same text.
  • What is the real complexity of the string version? Each key contains its whole subtree, so total key length can reach O(n²).
  • Return every copy, or the count per group. Keep a list per key instead of a counter.
  • Treat mirror images as equal. Order the two child ids before building the key.
  • Compare two separate trees for a shared subtree. Use one id table across both walks.

Brute force: serialize every subtree on its own

The direct approach visits each node and writes out its whole subtree as text, with a marker for every missing child, then groups nodes by that text. Any group of size two or more is a duplicate, and its first node goes in the answer. Each serialization writes out its whole subtree, and building that text by repeated concatenation copies it again at every level, so on a chain one call costs about m² character copies for m nodes and the whole loop reaches O(n³). Even with smarter string building it stays O(n²) on a chain. It is a good test reference because every key is built independently.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def serialize(node):
    if node is None:
        return "#"
    return "(" + serialize(node.left) + "," + str(node.val) + "," + serialize(node.right) + ")"

def find_duplicates_brute(root):
    groups = {}
    stack = [root] if root else []
    while stack:
        node = stack.pop()
        groups.setdefault(serialize(node), []).append(node)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    return [nodes[0] for nodes in groups.values() if len(nodes) > 1]
Python: fresh serialization for every node. Up to O(n³) on a chain. Our test reference.

Better: build each key once, bottom up

A parent's description is just its children's descriptions plus its own value. So a single post-order walk can return each subtree's key to its parent, and the parent glues the pieces together. Counting keys as they are created, and adding a node only when its key's count becomes exactly 2, reports each group once. This is the answer most people give, and it is correct.

from collections import Counter

def find_duplicates_strings(root):
    count = Counter()
    found = []

    def key(node):
        if node is None:
            return "#"
        k = key(node.left) + "," + key(node.right) + "," + str(node.val)
        count[k] += 1
        if count[k] == 2:
            found.append(node)
        return k

    key(root)
    return found
Python: one post-order pass with string keys. Correct, but keys can be long.

The catch is hidden in the concatenation. The root's key contains the entire tree, its children's keys contain almost all of it, and so on, so on a chain the total length of all keys is about n²/2 characters. Hashing and storing those strings is where the time goes, which makes this version O(n²) in the worst case even though it visits each node once.

Optimal: give every distinct subtree a small id

Replace each child's string with an integer that stands for it. An empty child is id 0. For a real node, form the triple (left id, value, right id) and look it up in a dictionary; if it is new, assign the next integer. Two subtrees get the same id exactly when their triples match, which by induction means their whole structures match. Every key is now three small numbers, so each lookup is constant time on average and the pass is O(n) expected.

def find_duplicates(root):
    ids = {}
    seen = {}
    found = []

    def get_id(node):
        if node is None:
            return 0
        triple = (get_id(node.left), node.val, get_id(node.right))
        if triple not in ids:
            ids[triple] = len(ids) + 1
        uid = ids[triple]
        seen[uid] = seen.get(uid, 0) + 1
        if seen[uid] == 2:
            found.append(node)
        return uid

    get_id(root)
    return found
Python: integer ids for (left id, value, right id) triples. O(n) expected time and space.

Both Python versions recurse once per level, so a chain deeper than about a thousand nodes needs a higher recursion limit or an explicit stack. The JavaScript version takes the explicit route: it lists nodes so that every parent precedes its children, then walks that list backward, which guarantees both child ids exist before the parent is keyed. The map key is a short string of three numbers, which keeps it constant size.

function findDuplicateSubtrees(root) {
  const found = [];
  if (root === null) return found;
  const order = [];
  const stack = [root];
  while (stack.length > 0) {
    const node = stack.pop();
    order.push(node);
    if (node.left !== null) stack.push(node.left);
    if (node.right !== null) stack.push(node.right);
  }
  const idOf = new Map();
  const tripleId = new Map();
  const seen = new Map();
  for (let i = order.length - 1; i >= 0; i--) {
    const node = order[i];
    const l = node.left === null ? 0 : idOf.get(node.left);
    const r = node.right === null ? 0 : idOf.get(node.right);
    const key = l + "," + node.val + "," + r;
    let id = tripleId.get(key);
    if (id === undefined) {
      id = tripleId.size + 1;
      tripleId.set(key, id);
    }
    idOf.set(node, id);
    const times = (seen.get(id) || 0) + 1;
    seen.set(id, times);
    if (times === 2) found.push(node);
  }
  return found;
}
JavaScript: the same id scheme without recursion. O(n) expected time.

Trace the example. Each leaf 2 gets the triple (0, 2, 0), which becomes id 1; the second time it appears, a leaf 2 is reported. A 4 with that leaf on its left is (1, 4, 0), id 2, and its second appearance reports it. The node 3 is (2, 3, 1), seen once, and the root is seen once, so the answer holds two nodes.

Complexity

n nodes, height h
ApproachTimeSpace
Serialize every subtree from scratchO(n²) characters of keys, up to O(n³) copying on a chainO(n²) for the stored keys in the worst case
One-pass post-order string keysO(n²) worst case from key lengthO(n²) worst case
Integer ids for (left, value, right)O(n) expectedO(n)
n nodes, height h. Scroll sideways on a small screen.

Edge cases

  • Empty tree or one node: no duplicates, return an empty list.
  • Every node has the same value: many shapes repeat, and each shape must still be reported once.
  • Mirror-image subtrees: not duplicates unless the problem says so.
  • Multi-digit and negative values: keys need separators so 1 and 12 cannot blur into 11 and 2.
  • A long chain: deep recursion and, for string keys, very long strings.

Mistakes to avoid

  • Leaving out null markers, or using in-order text. A 1 with a left child 1 and a 1 with a right child 1 both read "1,1" in order without markers.
  • Adding a node every time its key repeats, which lists a three-copy group twice.
  • Using the node's value alone, or value plus size, as the key.
  • Calling the string version O(n) without accounting for key length.
  • Comparing subtrees pairwise with a recursive equality check, which is O(n²) comparisons before any equality work.

How to explain it out loud

Fictional example

Moving from strings to ids
Candidate
Two subtrees are equal when their roots match and their left and right subtrees match, so I will describe each subtree from the bottom up, with a marker for missing children.
Candidate
I count each description and add the node when the count hits two, which reports each group once.
Interviewer
Is that linear?
Candidate
Not with strings, since the root's key holds the whole tree. If I give each distinct triple of left id, value and right id its own integer, every key is three numbers and it becomes linear on average.

Most Frequent Subtree Sum uses the same post-order counting but summarizes each subtree with a number instead of its shape. N-ary Tree Level Order Traversal is a breadth-first contrast, and Delete Node in a BST is good practice for reasoning about subtrees as units. For hash maps used to count things in general, see Top K Frequent Elements.

Rehearsing with Natively

Natively can look at a screenshot of a problem like this one during a practice session on your Mac or Windows PC and reply with an approach and code, so you can check whether your own key design handles missing children. Ask it a pointed question, such as why the string version is not linear, and it answers that instead. Recording a spoken run-through as a transcript also shows you where your explanation wandered. See how the AI interview assistant works.

Questions people ask

How do you find duplicate subtrees in a binary tree?

Walk the tree in post-order and build a key for each subtree from its children's keys and its own value, with a marker for missing children. Count the keys and add a node the moment its key's count reaches two.

Why does Find Duplicate Subtrees need null markers?

Without them, different shapes can produce the same text. A node 1 with a left child 1 and a node 1 with a right child 1 would look identical.

What is the time complexity of Find Duplicate Subtrees?

The string-key version is O(n²) in the worst case because keys contain whole subtrees. Mapping each (left id, value, right id) triple to an integer makes it O(n) expected time.

How do you report each duplicate only once?

Add the node only when its key's count becomes exactly 2. Later copies raise the count further but are not added again.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP