-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSolution652.java
40 lines (29 loc) · 872 Bytes
/
Solution652.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package leetcode.tree.dfs;
import leetcode.TreeNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Solution652 {
List<TreeNode> res;
HashMap<String, Integer> map;
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
res = new ArrayList<>();
map = new HashMap<>();
recursion(root);
return res;
}
private String recursion(TreeNode root) {
if (root == null) {
return " ";
}
StringBuilder nodes = new StringBuilder();
nodes.append(root.val).append("_");
nodes.append(recursion(root.left)).append(recursion(root.right));
String key = nodes.toString();
map.put(key, map.getOrDefault(key, 0) + 1);
if (map.get(key) == 2) {
res.add(root);
}
return key;
}
}