Skip to content

Commit 3615d8d

Browse files
authored
Add Solution To Tree Level Width (#135)
1 parent c16f481 commit 3615d8d

File tree

1 file changed

+30
-1
lines changed
  • src/test/kotlin/com/igorwojda/tree/classic/levelwidth

1 file changed

+30
-1
lines changed

src/test/kotlin/com/igorwojda/tree/classic/levelwidth/Solution.kt

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,35 @@
11
package com.igorwojda.tree.classic.levelwidth
22

33
private object Solution1 {
4+
private fun levelWidth(tree: Node): List<Int> {
5+
val nodesAtLevel = mutableListOf<Int>()
6+
7+
var levelNodes = listOf(tree)
8+
9+
while (levelNodes.isNotEmpty()) {
10+
nodesAtLevel.add(levelNodes.size)
11+
levelNodes = levelNodes.flatMap { it.children }
12+
}
13+
14+
return nodesAtLevel
15+
}
16+
17+
private class Node(val data: String, val children: MutableList<Node> = mutableListOf()) {
18+
fun add(data: String) {
19+
add(Node(data))
20+
}
21+
22+
fun add(node: Node) {
23+
children.add(node)
24+
}
25+
26+
fun remove(data: String) {
27+
children.removeAll { it.data == data }
28+
}
29+
}
30+
}
31+
32+
private object Solution2 {
433
private fun levelWidth(tree: Node): List<Int> {
534
val result = mutableListOf<Int>()
635

@@ -41,7 +70,7 @@ private object Solution1 {
4170
}
4271
}
4372

44-
private object Solution2 {
73+
private object Solution3 {
4574
// Counters array solution
4675
private fun levelWidth(tree: Node): List<Int> {
4776
val rowSeparator = null

0 commit comments

Comments
 (0)