Find all Duplicate subtrees in a Binary tree
Pattern: Serialise and deserialise
Build a key for every subtree bottom up and count keys in a map. When a key's count reaches exactly 2, add that subtree's root to the answer, so each kind of duplicate is reported once.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Return one root for every kind of subtree that appears more than once (same shape and values). The tests print each
returned subtree in level order and sort the list. The example gives [[2, 4], [4]]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- How do you know two subtrees are equal?
- When should a subtree be reported?
- Why not report it every time?
Hints
Brute force, and why it fails
Compare every pair of subtrees: O(n³).
The key insight
Counting keys in one bottom-up pass finds every repeated kind at the moment it first repeats.
Dry run
| count(4) | 3 |
|---|
Tree [1, 2, 3, 4, null, 2, 4, null, null, 4]. Keys: leaf 4 appears three times.
The plan
key(n): if null: "#"
k = "(" + n.val + "," + key(left) + "," + key(right) + ")"
count[k] += 1; if count[k] == 2: out.add(n)
return k
Complexity
- Time
O(n²)- Space
O(n²)
Key strings can be long; numbering keys makes it O(n).
Edge cases
- No duplicates: empty list.
- Many copies of one leaf: reported once.
- One node.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
Map<String, Integer> count = new HashMap<>();
List<TreeNode> out = new ArrayList<>();
key(root, count, out);
return out;
}
private String key(TreeNode n, Map<String, Integer> count, List<TreeNode> out) {
if (n == null) return "#";
String k = "(" + n.val + "," + key(n.left, count, out) + "," + key(n.right, count, out) + ")";
int seen = count.merge(k, 1, Integer::sum);
if (seen == 2) out.add(n); // report each kind once, the second time it appears
return k;
}
}C++
class Solution {
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
unordered_map<string, int> count;
vector<TreeNode*> out;
key(root, count, out);
return out;
}
string key(TreeNode* n, unordered_map<string, int>& count, vector<TreeNode*>& out) {
if (n == NULL) return "#";
string k = "(" + to_string(n->val) + "," + key(n->left, count, out) + "," + key(n->right, count, out) + ")";
if (++count[k] == 2) out.push_back(n); // report each kind once, the second time it appears
return k;
}
};Python
class Solution:
def findDuplicateSubtrees(self, root) -> list:
count, out = {}, []
def key(n) -> str:
if n is None:
return "#"
k = f"({n.val},{key(n.left)},{key(n.right)})"
count[k] = count.get(k, 0) + 1
if count[k] == 2:
out.append(n) # report each kind once, the second time it appears
return k
key(root)
return outCommon mistakes
- Reporting on every repeat.
- Keys that ignore empty children.