Find Duplicate Subtrees
Master this topic with zero to advance depth.
Find Duplicate Subtrees
List duplicates.
Level I: Brute Force (Recursive Comparison)
Intuition
For every node in the tree, we can compare its subtree with the subtrees of all other nodes. This involves a nested traversal: for each node, we start a secondary traversal that checks for equality with every other node.
Logic
dfs(node)visits every node.- For each node,
isSame(node, otherNode)checks if they are identical. - Very slow ( or depending on implementation).
Detailed Dry Run
Compare Node(2) with every other node in the tree. If equal and not seen before, add to result.
Level II: Serialization with Map
Intuition
How do we know if two subtrees are identical? We can serialize each subtree (convert to string) and store the frequency of these strings in a HashMap. If a string appears for the second time, we've found a duplicate.
Logic
- Use Post-order DFS.
- For each node, string =
val + "," + left + "," + right. - Add string to Map.
- If
map.get(string) == 2, add current node to results.
Detailed Dry Run
| Node | Left Serial | Right Serial | Node Serial | Count | Duplicate? |
|---|---|---|---|---|---|
| Leaf 4 | # | # | "4,#,#" | 1 | NO |
| Leaf 4 | # | # | "4,#,#" | 2 | YES! |
| Node 2 | "4,#,#" | # | "2,4,#,#,#" | 1 | NO |
Level III: Optimal (Integer ID Mapping)
Intuition
Thought Process
The bottleneck in Level II is caused by string concatenation. Instead of strings, we can assign a unique integer ID to each subtree structure. Two subtrees are identical if they have the same (node.val, left_child_id, right_child_id) triplet.
Logic
- Use a Map
tripletToIDto map triplets of integers to a unique ID. - Use a Map
idCountto track how many times each ID has appeared. - This reduces the problem to because triplet comparison is .
Detailed Dry Run
| Node | Left ID | Right ID | Triplet | New ID | Count | Duplicate? |
|---|---|---|---|---|---|---|
| 4 | 0 | 0 | (4,0,0) | 1 | 1 | NO |
| 4 | 0 | 0 | (4,0,0) | 1 | 2 | YES! |
| 2 | 1 | 0 | (2,1,0) | 2 | 1 | NO |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.