@@ -31,7 +31,7 @@ public List<Node> findEquivalentSubtrees(Node root) {
31
31
}
32
32
33
33
// Fill `vocabulary` field of nodes
34
- buildNodeVocabulary (root );
34
+ fillNodeVocabulary (root );
35
35
36
36
// Build Set<Character> -> List<Node> map
37
37
Map <Set <Character >, List <Node >> voc2Nodes = new HashMap <>();
@@ -54,15 +54,8 @@ public List<Node> findEquivalentSubtrees(Node root) {
54
54
voc2Nodes .get (vocabulary ).add (current );
55
55
}
56
56
57
- // Found equivalent nodes
58
57
return voc2Nodes .values ().stream ()
59
- .filter (entry -> entry .size () >= 2 )
60
- .map (
61
- entry -> entry .stream ()
62
- .sorted ((o1 , o2 ) -> o2 .vocabulary .size () - o1 .vocabulary .size ())
63
- .limit (2 )
64
- .toList ()
65
- )
58
+ .filter (nodesList -> nodesList .size () >= 2 )
66
59
.sorted ((o1 , o2 ) -> o2 .stream ().mapToInt (nodeToIntFunction ()).sum () - o1 .stream ().mapToInt (nodeToIntFunction ()).sum ())
67
60
.limit (1 )
68
61
.findFirst ().orElse (null );
@@ -72,14 +65,14 @@ private static ToIntFunction<Node> nodeToIntFunction() {
72
65
return node -> node .vocabulary .size ();
73
66
}
74
67
75
- private Set <Character > buildNodeVocabulary (Node node ) {
68
+ private Set <Character > fillNodeVocabulary (Node node ) {
76
69
if (node .left != null ) {
77
70
node .vocabulary .add (node .left .value );
78
- node .vocabulary .addAll (buildNodeVocabulary (node .left ));
71
+ node .vocabulary .addAll (fillNodeVocabulary (node .left ));
79
72
}
80
73
if (node .right != null ) {
81
74
node .vocabulary .add (node .right .value );
82
- node .vocabulary .addAll (buildNodeVocabulary (node .right ));
75
+ node .vocabulary .addAll (fillNodeVocabulary (node .right ));
83
76
}
84
77
return node .vocabulary ;
85
78
}
0 commit comments