1
+ // Runtime: 1783 ms (Top 5.02%) | Memory: 64.5 MB (Top 11.80%)
1
2
/**
2
3
* Definition for a binary tree node.
3
4
* public class TreeNode {
4
- * int val;
5
- * TreeNode left;
6
- * TreeNode right;
7
- * TreeNode() {}
8
- * TreeNode(int val) { this.val = val; }
9
- * TreeNode(int val, TreeNode left, TreeNode right) {
10
- * this.val = val;
11
- * this.left = left;
12
- * this.right = right;
13
- * }
5
+ * int val;
6
+ * TreeNode left;
7
+ * TreeNode right;
8
+ * TreeNode() {}
9
+ * TreeNode(int val) { this.val = val; }
10
+ * TreeNode(int val, TreeNode left, TreeNode right) {
11
+ * this.val = val;
12
+ * this.left = left;
13
+ * this.right = right;
14
+ * }
14
15
* }
15
16
*/
16
17
class Solution {
@@ -19,40 +20,38 @@ public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
19
20
HashSet <String > hashes = new HashSet <String >();
20
21
HashSet <String > added = new HashSet <String >();
21
22
22
-
23
23
// for each node, perform a dfs traversal and generate a hash
24
- // check if the hash already exists in a set,
24
+ // check if the hash already exists in a set,
25
25
// if it does, get the treenode and add it to the list
26
26
Stack <TreeNode > s = new Stack <TreeNode >();
27
-
27
+
28
28
s .add (root );
29
29
while (!s .isEmpty ()){
30
30
TreeNode tmp = s .pop ();
31
31
dfs (tmp , "" , tmp , list , hashes , added );
32
-
32
+
33
33
if (tmp .left != null ){
34
34
s .add (tmp .left );
35
35
}
36
36
if (tmp .right != null ){
37
37
s .add (tmp .right );
38
38
}
39
39
}
40
-
40
+
41
41
return list ;
42
-
42
+
43
43
}
44
-
44
+
45
45
public void dfs (TreeNode parent , String hash , TreeNode root , List <TreeNode > list , HashSet <String > set , HashSet <String > added ){
46
-
46
+
47
47
Stack <TreeNode > stack = new Stack <TreeNode >();
48
-
48
+
49
49
stack .add (root );
50
50
//String hash = "";
51
51
hash += root .val + "ROOT," ;
52
52
while (!stack .isEmpty ()){
53
53
TreeNode tmp = stack .pop ();
54
54
//hash += tmp.val + ",";
55
-
56
55
57
56
if (tmp .left != null ){
58
57
hash += tmp .left .val + "L," ;
@@ -80,7 +79,7 @@ public void dfs(TreeNode parent, String hash, TreeNode root, List<TreeNode> list
80
79
}
81
80
return ;
82
81
}
83
-
82
+
84
83
}
85
84
}
86
- }
85
+ }
0 commit comments