Skip to content
Snippets Groups Projects
Commit abcb9f3e authored by Kaj Koivunen's avatar Kaj Koivunen :coffee:
Browse files

binäärisen hakupuun toteutus

parent 1c7ff359
No related branches found
No related tags found
No related merge requests found
package guru.kake.ronove
class BST<T : Comparable<T>>(list: List<T>) {
private var root: Node<T>? = null
init {
val list2 = list.sorted()
root = Node(list2[list2.size/2])
createBST(list2, root!!)
}
private fun createBST(children: List<T>, parent: Node<T>) {
val left = children.subList(0, children.size / 2)
val right = children.subList(children.size / 2 + 1, children.size)
if (left.isNotEmpty()) {
parent.left = Node(left[left.size / 2])
createBST(left, parent.left!!)
}
if (right.isNotEmpty()) {
parent.right = Node(right[right.size / 2])
createBST(right, parent.right!!)
}
}
fun find(value: T): T? {
var node = root
while (true) {
if (node!=null) {
if (node.value < value) {
node = node.right
continue
}
else if (node.value > value) {
node = node.left
continue
}
}
return node?.value
}
}
@Deprecated(message = "Will not be part of the final API")
fun debugFind(value: T): List<T?> {
val list = mutableListOf<T>()
var node = root
while (true) {
if (node!=null) {
println("node: ${node.value}, left: ${node.left?.value}, right: ${node.right?.value}")
list.add(node.value)
if (node.value < value) {
node = node.right
continue
}
else if (node.value > value) {
node = node.left
continue
}
}
break
}
return list.toList()
}
class Node<T>(val value: T) {
var left: Node<T>? = null
var right: Node<T>? = null
}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment