-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFindDuplicateSubtrees.java
39 lines (30 loc) · 1023 Bytes
/
FindDuplicateSubtrees.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
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.*;
// https://leetcode.com/problems/find-duplicate-subtrees/
public class FindDuplicateSubtrees {
private final Set<TreeNode> duplicates = new HashSet<>();
private final Map<String, TreeNode> nodes = new HashMap<>();
private final TreeNode input;
public FindDuplicateSubtrees(TreeNode input) {
this.input = input;
}
public List<TreeNode> solution() {
traverse(input);
return new ArrayList<>(duplicates);
}
private String traverse(TreeNode node) {
if (node == null) {
return "";
}
String left = traverse(node.left);
String right = traverse(node.right);
String curr = left + " " + right + " " + node.val;
if (nodes.containsKey(curr)) {
duplicates.add(nodes.get(curr));
} else {
nodes.put(curr, node);
}
return curr;
}
}