-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
56 lines (49 loc) · 1.24 KB
/
Solution.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* 类描述:
*
* @ClassName Solution
* @Description TODO
* @Author BaiMohan
* @Date 2021/3/1 16:09
* @Version 1.0
*/
public class Solution {
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;
}
}
HashMap<String, Integer> hashMap = new HashMap<>();
LinkedList<TreeNode> linkedList = new LinkedList<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
traverse(root);
return linkedList;
}
public String traverse(TreeNode root) {
if (null == root) {
return "#";
}
String left = traverse(root.left);
String right = traverse(root.right);
String path = left + "," + right + "," + root.val;
int fre = hashMap.getOrDefault(path, 0);
if (1 == fre) {
linkedList.add(root);
}
hashMap.put(path, fre + 1);
return path;
}
}