forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 17
/
BinaryTree.kt
45 lines (38 loc) Β· 1.13 KB
/
BinaryTree.kt
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
package algo.datastructures.tree
import algo.datastructures.Queue
class BinaryTree(var value: Int, var left: BinaryTree?, var right: BinaryTree?) {
constructor(value: Int): this(value, null, null)
fun size(): Int {
var size = 1
if (left != null) {
size += left!!.size()
}
if (right != null) {
size += right!!.size()
}
return size
}
fun height(): Int {
val left = if (left == null) 0 else left!!.height()
val right = if (right == null) 0 else right!!.height()
return maxOf(left, right) + 1
}
fun add(value: Int) {
// adds the on the first empty level
val queue = Queue<BinaryTree>()
queue.add(this)
while (!queue.isEmpty()) {
val x = queue.poll()
if (x.left == null) {
x.left = BinaryTree(value)
return
} else if (x.right == null) {
x.right = BinaryTree(value)
return
} else {
queue.add(x.left!!)
queue.add(x.right!!)
}
}
}
}