Skip to content

Commit 607ad68

Browse files
committed
Cover one more case for EquivalentNodesOfTree. Tired of it
1 parent afd9862 commit 607ad68

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

src/main/java/by/andd3dfx/tree/equivalent/EquivalentNodesOfTree.java

+8-5
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import java.util.List;
88
import java.util.Map;
99
import 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) {

src/test/java/by/andd3dfx/tree/equivalent/EquivalentNodesOfTreeTest.java

+4-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
import java.util.List;
77

8-
import static org.hamcrest.CoreMatchers.hasItem;
98
import static org.hamcrest.CoreMatchers.hasItems;
109
import static org.hamcrest.CoreMatchers.is;
1110
import 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
}

0 commit comments

Comments
 (0)