@@ -62,12 +62,10 @@ class BinarySearchTree<K: Comparable<K>, V>: Map<K, V> {
62
62
override fun get (key : K ): V ? {
63
63
var x = root
64
64
while (x != null ) {
65
- if (key < x.key) {
66
- x = x.left
67
- } else if (key > x.key) {
68
- x = x.right
69
- } else {
70
- return x.value
65
+ x = when {
66
+ key < x.key -> x.left
67
+ key > x.key -> x.right
68
+ else -> return x.value
71
69
}
72
70
}
73
71
return null
@@ -87,12 +85,10 @@ class BinarySearchTree<K: Comparable<K>, V>: Map<K, V> {
87
85
88
86
private fun add (key : K , value : V , x : Node <K , V >? ): Node <K , V > {
89
87
if (x == null ) return Node (key, value)
90
- if (key < x.key) {
91
- x.left = add(key, value, x.left)
92
- } else if (key > x.key) {
93
- x.right = add(key, value, x.right)
94
- } else {
95
- x.value = value
88
+ when {
89
+ key < x.key -> x.left = add(key, value, x.left)
90
+ key > x.key -> x.right = add(key, value, x.right)
91
+ else -> x.value = value
96
92
}
97
93
x.size = size(x.left) + size(x.right) + 1
98
94
return x
@@ -104,25 +100,23 @@ class BinarySearchTree<K: Comparable<K>, V>: Map<K, V> {
104
100
105
101
private fun remove (key : K , root : Node <K , V >? ): Node <K , V >? {
106
102
var x: Node <K , V > = root ? : throw NoSuchElementException ()
107
- if (key < x.key) {
108
- x.left = remove(key, x.left)
109
- } else if ( key > x.key) {
110
- x.right = remove(key, x.right)
111
- } else {
112
- if (x.left == null ) return x.right
113
- if (x.right == null ) return x.left
114
- val tmp = x
115
- x = pollMin (tmp.right!! ) !!
116
- x.right = min( tmp.right)
117
- x.left = tmp.left
103
+ when {
104
+ key < x.key -> x.left = remove(key, x.left)
105
+ key > x.key -> x.right = remove(key, x.right)
106
+ else -> {
107
+ if (x.left == null ) return x.right
108
+ if (x.right == null ) return x.left
109
+ val tmp = x
110
+ x = pollMin(tmp.right !! ) !!
111
+ x.right = min (tmp.right)
112
+ x.left = tmp.left
113
+ }
118
114
}
119
- x.size = size(x.left) + size(x.right) + 1 ;
115
+ x.size = size(x.left) + size(x.right) + 1
120
116
return x
121
117
}
122
118
123
- private fun size (x : Node <K , V >? ): Int {
124
- if (x == null ) return 0 else return x.size
125
- }
119
+ private fun size (x : Node <K , V >? ): Int = x?.size ? : 0
126
120
127
121
fun height (): Int {
128
122
return height(root)
0 commit comments