Skip to content

Commit 8f3efb0

Browse files
committed
Simplify solution of EquivalentTrees task (a bit more)
1 parent 185f2cd commit 8f3efb0

File tree

2 files changed

+5
-15
lines changed

2 files changed

+5
-15
lines changed

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

+5-12
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public List<Node> findEquivalentSubtrees(Node root) {
3131
}
3232

3333
// Fill `vocabulary` field of nodes
34-
buildNodeVocabulary(root);
34+
fillNodeVocabulary(root);
3535

3636
// Build Set<Character> -> List<Node> map
3737
Map<Set<Character>, List<Node>> voc2Nodes = new HashMap<>();
@@ -54,15 +54,8 @@ public List<Node> findEquivalentSubtrees(Node root) {
5454
voc2Nodes.get(vocabulary).add(current);
5555
}
5656

57-
// Found equivalent nodes
5857
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)
6659
.sorted((o1, o2) -> o2.stream().mapToInt(nodeToIntFunction()).sum() - o1.stream().mapToInt(nodeToIntFunction()).sum())
6760
.limit(1)
6861
.findFirst().orElse(null);
@@ -72,14 +65,14 @@ private static ToIntFunction<Node> nodeToIntFunction() {
7265
return node -> node.vocabulary.size();
7366
}
7467

75-
private Set<Character> buildNodeVocabulary(Node node) {
68+
private Set<Character> fillNodeVocabulary(Node node) {
7669
if (node.left != null) {
7770
node.vocabulary.add(node.left.value);
78-
node.vocabulary.addAll(buildNodeVocabulary(node.left));
71+
node.vocabulary.addAll(fillNodeVocabulary(node.left));
7972
}
8073
if (node.right != null) {
8174
node.vocabulary.add(node.right.value);
82-
node.vocabulary.addAll(buildNodeVocabulary(node.right));
75+
node.vocabulary.addAll(fillNodeVocabulary(node.right));
8376
}
8477
return node.vocabulary;
8578
}

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

-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package by.andd3dfx.tree.equivalent;
22

3-
import lombok.Getter;
4-
53
import java.util.HashSet;
64
import java.util.Set;
75

@@ -10,7 +8,6 @@ public class Node {
108
Node left;
119
Node right;
1210

13-
@Getter
1411
Set<Character> vocabulary = new HashSet<>();
1512

1613
public Node(char value) {

0 commit comments

Comments
 (0)