1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
class Solution {
ArrayList<TreeNode> res = new ArrayList<>();
HashMap<String, Integer> map = new HashMap<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
traverse(root);
return res;
}
private String traverse(TreeNode root) {
if (root == null)
return "#";
String left = traverse(root.left);
String right = traverse(root.right);
String temp = left + "," + right + "," + String.valueOf(root.val);
map.put(temp, map.getOrDefault(temp, 0) + 1);
int freq = map.get(temp);
if (freq == 2) {
res.add(root);
}
return temp;
}
}
|