0%

Kotlin实现二叉排序树(Binary Sort Tree)的插入

使用Kotlin语言实现二叉排序树,并将一个数组插入。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
fun main(args: Array<String>) {
val nodes: IntArray = intArrayOf(8, 3, 10, 1, 6, 14, 4, 7, 13)
val binaryTree = BinaryTree()
nodes.forEach { binaryTree.insert(it) }
}

class BinaryTree {
var root: Node? = null

private fun insertNode(node: Node, newNode: Node) {
if (newNode.key < node.key) {
if (node.left == null) {
node.left = newNode
} else {
insertNode(node.left!!, newNode);
}
} else {
if (node.right == null) {
node.right = newNode
} else {
insertNode(node.right!!, newNode)
}
}
}

fun insert(key: Int) {
val newNode = Node(key)
if (root == null) {
root = newNode
} else {
insertNode(root!!, newNode)
}
}

}

class Node(var key: Int) {
var left: Node? = null
var right: Node? = null
}