Martin Nordholts
10/17/2019, 1:48 PM!!
in below code without getting compilation errors and without getting ugly code? Edit: And without recursion
class Node(val child: Node?)
fun Node.getLeaf(): Node {
var candidate: Node = this
while (candidate.child != null) {
candidate = candidate.child!!
}
return candidate
}
thanksforallthefish
10/17/2019, 1:54 PMfun Node.getLeaf() : Node = findLeaf(this)
tailrec fun findLeaf(candidate: Node) {
val child = candidate.child
if(child == null) return candidate
return findLeaf(child)
}
Svyatoslav Kuzmich [JB]
10/17/2019, 1:54 PMwhile (true) {
candidate = candidate.child ?: break
}
Martin Nordholts
10/17/2019, 1:55 PMwbertan
10/17/2019, 1:58 PMtailrec fun Node.getLeaf(): Node = when (child) {
null -> this
else -> child.getLeaf()
}
My 2 cents 🙂
@Test
fun asas() {
val nodes =
Node(
0,
Node(
1,
Node(2, null)
)
)
assertEquals(Node(2, null), nodes.getLeaf())
}
thanksforallthefish
10/17/2019, 2:00 PM