leetcode-652-Find-Duplicate-Subtrees

描述


Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any oneof them.

Two trees are duplicate if they have the same structure with same node values.

Example 1:

1
2
3
4
5
6
7
    1
/ \
2 3
/ / \
4 2 4
/
4

The following are two duplicate subtrees:

1
2
3
  2
/
4

and

1
4

Therefore, you need to return above trees’ root in the form of a list.

分析


先序遍历,把路径序列化为字符串作为 map 的 key。

解决方案1(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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
List<TreeNode> result = new ArrayList<>();
if (root == null) {
return result;
}
preOrder(root, result, new HashMap<String, Integer>());
return result;
}

private String preOrder(TreeNode node, List<TreeNode> result, Map<String, Integer> map) {
if (node == null) {
return "#";
}
String mapKey = node.val + "," + preOrder(node.left, result, map) + "," + preOrder(node.right, result, map);
if (map.getOrDefault(mapKey, 0) == 1) {
result.add(node);
}
map.put(mapKey, map.getOrDefault(mapKey, 0) + 1);
return mapKey;
}
}

相关问题


题目来源