-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.kt
More file actions
75 lines (61 loc) · 1.4 KB
/
bst.kt
File metadata and controls
75 lines (61 loc) · 1.4 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
fun main(args: Array<String>) {
println("Hello")
var t = Tree<Int>()
t.add(1)
t.add(2)
t.add(3)
t.add(4)
t.add(5)
t.BFT()
var t2 = Tree<Int>()
t2.add(10)
t2.add(11)
t2.add(12)
t2.add(1)
t2.add(2)
t2.BFT()
}
class Node<T: Comparable<T>>(val value: T?=null) {
var left: Node<T>? = null
var right: Node<T>? = null
}
class Tree<T : Comparable<T>>() {
var root: Node<T>? = null
fun add(item: T): Unit {
var n: Node<T> = Node<T>(item)
if (root == null) {
root = n
return
}
var cur = root
while (cur != null) {
if (item > cur.value!!) {
if (cur.right == null) {
cur.right = n
break
}
cur = cur.right
} else {
if (cur.left == null) {
cur.left = n
break
}
cur = cur.left
}
}
}
fun BFT() {
if (root == null) return
var q = mutableListOf<Node<T>>(root!!)
while(q.size!=0){
var cur = q.removeAt(0)
println("${cur.value} ->")
if (cur.left != null) {
q.add(cur.left!!)
}
if (cur.right != null) {
q.add(cur.right!!)
}
}
}
}