File tree 2 files changed +12
-8
lines changed
main/java/by/andd3dfx/tree/equivalent
test/java/by/andd3dfx/tree/equivalent
2 files changed +12
-8
lines changed Original file line number Diff line number Diff line change 7
7
import java .util .List ;
8
8
import java .util .Map ;
9
9
import java .util .Set ;
10
- import java .util .function .ToIntFunction ;
11
10
12
11
/**
13
12
* <pre>
@@ -60,13 +59,17 @@ public List<Node> findEquivalentNodes(Node root) {
60
59
61
60
return voc2NodesMap .values ().stream ()
62
61
.filter (nodes -> nodes .size () >= 2 )
63
- .min (( o1 , o2 ) -> o2 .stream ().mapToInt ( nodeToIntFunction ()). sum () - o1 . stream (). mapToInt ( nodeToIntFunction ()). sum ())
64
- .map ( nodes -> nodes . subList ( 0 , 2 ) )
62
+ .map ( nodes -> nodes .stream ().sorted ( this :: compare ). limit ( 2 ). toList ())
63
+ .min ( this :: compare )
65
64
.orElse (null );
66
65
}
67
66
68
- private static ToIntFunction <Node > nodeToIntFunction () {
69
- return node -> node .subtreeSize ;
67
+ private int compare (Node n1 , Node n2 ) {
68
+ return n2 .subtreeSize - n1 .subtreeSize ;
69
+ }
70
+
71
+ private int compare (List <Node > list1 , List <Node > list2 ) {
72
+ return list2 .stream ().mapToInt (node -> node .subtreeSize ).sum () - list1 .stream ().mapToInt (node -> node .subtreeSize ).sum ();
70
73
}
71
74
72
75
private Set <Character > fillNodeVocabulary (Node node ) {
Original file line number Diff line number Diff line change 5
5
6
6
import java .util .List ;
7
7
8
- import static org .hamcrest .CoreMatchers .hasItem ;
9
8
import static org .hamcrest .CoreMatchers .hasItems ;
10
9
import static org .hamcrest .CoreMatchers .is ;
11
10
import static org .hamcrest .CoreMatchers .nullValue ;
@@ -155,6 +154,8 @@ public void findEquivalentNodesAsymmetricCaseShouldChooseNodesWithMaxSubtreeSize
155
154
* D E D
156
155
* / \
157
156
* D E
157
+ * /
158
+ * D
158
159
* </pre>
159
160
*/
160
161
@ Test
@@ -172,11 +173,11 @@ public void findEquivalentNodesComplexCase() {
172
173
root .right .right .right = new Node ('D' );
173
174
root .right .right .right .left = new Node ('D' );
174
175
root .right .right .right .right = new Node ('E' );
176
+ root .right .right .right .left .left = new Node ('D' );
175
177
176
178
List <Node > result = equivalentNodesOfTree .findEquivalentNodes (root );
177
179
178
180
assertThat ("Two nodes expected" , result .size (), is (2 ));
179
- assertThat ("Left node is absent" , result , hasItem (root .left ));
180
- assertThat ("Right node is absent" , result , hasItem (root .right .right ));
181
+ assertThat (result , hasItems (root .right .right , root .right .right .right ));
181
182
}
182
183
}
You can’t perform that action at this time.
0 commit comments