Skip to content

Instantly share code, notes, and snippets.

@Telewa
Created April 17, 2020 19:54
Show Gist options
  • Save Telewa/7fd23d48b7c40675dc311e1d0634c804 to your computer and use it in GitHub Desktop.
Save Telewa/7fd23d48b7c40675dc311e1d0634c804 to your computer and use it in GitHub Desktop.
Insert items to a binary tree in kotlin
package com.emma.recursion
import kotlin.test.assertEquals
/**
* Insert items to a binary tree
*
* The side effect is, if the tree is printed with an inorder traversal, the items are sorted in asc order
*
* Worst complexity: n * log(n) (balanced)
* Average complexity: n * log(n)
* Best complexity: n * log(n)
* Space complexity: n
*
*/
class Node(private val value: Int) {
private var leftNode: Node? = null
private var rightNode: Node? = null
fun addNode(newNode: Node) {
when {
newNode.value >= value -> {
when (rightNode) {
null -> rightNode = newNode
else -> rightNode!!.addNode(newNode)
}
}
newNode.value < value -> {
when (leftNode) {
null -> leftNode = newNode
else -> leftNode!!.addNode(newNode)
}
}
}
}
override fun toString(): String {
var response = ""
if (leftNode != null) response += "$leftNode, "
response += value
if (rightNode != null) response += ", $rightNode"
return response
}
}
fun main() {
val itemsToSort = arrayOf(5, 8, 1, 3, 2, 4, 7, -1)
val tree = Node(itemsToSort[0])
for (item in 1..itemsToSort.lastIndex) {
tree.addNode(Node(itemsToSort[item]))
}
println(tree)
assertEquals(tree.toString(), "-1, 1, 2, 3, 4, 5, 7, 8", "bug in the sorting algorithmn :-(")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment