LC.P652[寻找重复的子树]

方法一:序列化+DFS

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {

Map<String, Integer> map = new HashMap<>();
List<TreeNode> ans = new ArrayList<>();

public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
dfs(root);
return ans;
}

// 序列化二叉树,如果某一个结果已经出现过一次,就发现了一类重复子树
private String dfs(TreeNode node) {
if (node == null) return " ";
StringBuilder builder = new StringBuilder();
builder.append(node.val).append("_");
builder.append(dfs(node.left)).append(dfs(node.right));
String key = builder.toString();
map.merge(key, 1, Integer::sum);
if (map.get(key) == 2) ans.add(node);
return key;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n)$