File tree Expand file tree Collapse file tree 2 files changed +12
-8
lines changed
main/java/by/andd3dfx/tree/equivalent
test/java/by/andd3dfx/tree/equivalent Expand file tree Collapse file tree 2 files changed +12
-8
lines changed Original file line number Diff line number Diff line change 77import java .util .List ;
88import java .util .Map ;
99import java .util .Set ;
10- import java .util .function .ToIntFunction ;
1110
1211/**
1312 * <pre>
@@ -60,13 +59,17 @@ public List<Node> findEquivalentNodes(Node root) {
6059
6160 return voc2NodesMap .values ().stream ()
6261 .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 )
6564 .orElse (null );
6665 }
6766
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 ();
7073 }
7174
7275 private Set <Character > fillNodeVocabulary (Node node ) {
Original file line number Diff line number Diff line change 55
66import java .util .List ;
77
8- import static org .hamcrest .CoreMatchers .hasItem ;
98import static org .hamcrest .CoreMatchers .hasItems ;
109import static org .hamcrest .CoreMatchers .is ;
1110import static org .hamcrest .CoreMatchers .nullValue ;
@@ -155,6 +154,8 @@ public void findEquivalentNodesAsymmetricCaseShouldChooseNodesWithMaxSubtreeSize
155154 * D E D
156155 * / \
157156 * D E
157+ * /
158+ * D
158159 * </pre>
159160 */
160161 @ Test
@@ -172,11 +173,11 @@ public void findEquivalentNodesComplexCase() {
172173 root .right .right .right = new Node ('D' );
173174 root .right .right .right .left = new Node ('D' );
174175 root .right .right .right .right = new Node ('E' );
176+ root .right .right .right .left .left = new Node ('D' );
175177
176178 List <Node > result = equivalentNodesOfTree .findEquivalentNodes (root );
177179
178180 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 ));
181182 }
182183}
You can’t perform that action at this time.
0 commit comments