Skip to content
Problem 652 · LeetCode 652(opens in a new tab)

Find Duplicate Subtrees

MediumHash tables

You get the root of a binary tree. Two subtrees count as duplicates when they have the same shape and the same value in every matching position.

Return one root node for every kind of subtree that appears two or more times. Each repeated kind is listed once, by any one of its copies, and the list can be in any order.

Example 1

Input:  root = [6, 4, 0, 2, null, 4, 2, null, null, 2]
Output: [[2], [4, 2]]
Why:    the leaf 2 shows up three times, and 4 with a left 2 twice
2 more examples and the constraints

Example 2

Input:  root = [5, 8, 8]
Output: [[8]]
Why:    the two leaves are both 8

Example 3

Input:  root = [1, 2, 3]
Output: []
Why:    every subtree is different

Constraints

  • 1 ≤ number of nodes ≤ 5,000
  • −200 ≤ Node.val ≤ 200

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Serialize every subtreeO(n²)
  2. Give each shape an idO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 5,000-node chainVerdict
Serialize every subtreeO(n²)
Passes; simple to say
Give each shape an idO(n)
Best; short keys, no copying

n = number of nodes. Results are drawn as level-order arrays.

Edge cases to test

  • A single node. Nothing can repeat, so return an empty list.
  • Mirror images. A 2 with a left 3 and a 2 with a right 3 are different shapes; only the leaves 3 repeat.
  • Three or more copies. Report the shape once, on its second sighting.
  • Values that glue together. Without separators, 1 then 11 and 11 then 1 both read "111". Use commas and a mark for empty children.

Common mistakes

  • Leaving out the marker for empty children, so a left child and a right child look the same.
  • Appending on every sighting after the first, which lists one shape many times.
  • Walking in pre-order and comparing before the children are known.

How to talk through it

  1. 1Clarify. Do equal values in a different shape count? Should each repeated shape be returned once?
  2. 2Describe a subtree. Its value plus its two children's descriptions, built bottom-up in post-order.
  3. 3Give the string version. Serialize and count; say the strings make it O(n²) on a chain.
  4. 4Swap strings for ids. Key each node by (left id, val, right id) so every key is three numbers.
  5. 5Test out loud. Run a single node, mirror images and a shape with three copies before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?