[Leetcode] Problem 652 - Find Duplicate Subtrees

Given the root of a binary tree, return all duplicate subtrees.

For each kind of duplicate subtrees, you only need to return the root node of any one of them.

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

Example

No.1

0cEQTU.jpg

Input: root = [1,2,3,4,null,2,4,null,null,4]

Output: [[2,4],[4]]

No.2

0cEJp9.jpg

Input: root = [2,1,1]

Output: [[1]]

No.3

0cEam6.jpg

Input: root = [2,2,2,3,null,3,null]

Output: [[2,3],[3]]

Constraints

  • The number of the nodes in the tree will be in the range [1, 10^4]
  • -200 <= Node.val <= 200

Code

1
2
3
4
5
6
7
8
9
10
11
12
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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private Map<String, int[]> count = new HashMap<>();
private int id = 0;

public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
List<TreeNode> duplicate = new ArrayList<>();
dfs(duplicate, root);
return duplicate;
}

private int dfs(List<TreeNode> duplicate, TreeNode root) {
if (root == null)
return 0;

String key = root.val + "," + dfs(duplicate, root.left) + "," + dfs(duplicate, root.right);
int[] array = count.computeIfAbsent(key, a -> new int[] {++id, 0});

if (++array[1] == 2)
duplicate.add(root);

return array[0];
}