Skip to content

Commit

Permalink
feat(datastructures/tree): binary search tree remove key
Browse files Browse the repository at this point in the history
  • Loading branch information
bmaslakov committed May 22, 2017
1 parent e007609 commit f90d647
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,28 @@ class BinarySearchTree<K: Comparable<K>, V> {
return x
}

fun remove(key: K) {
root = remove(key, root)
}

private fun remove(key: K, root: Node<K, V>?): Node<K, V>? {
var x: Node<K, V> = root ?: throw NoSuchElementException()
if (key < x.key) {
x.left = remove(key, x.left)
} else if (key > x.key) {
x.right = remove(key, x.right)
} else {
if (x.left == null) return x.right
if (x.right == null) return x.left
val tmp = x
x = pollMin(tmp.right!!)!!
x.right = min(tmp.right)
x.left = tmp.left
}
x.size = size(x.left) + size(x.right) + 1;
return x
}

fun size(): Int {
return size(root)
}
Expand All @@ -73,21 +95,29 @@ class BinarySearchTree<K: Comparable<K>, V> {
}

fun min(): K {
if (root == null) throw NoSuchElementException()
var x = root!!
return min(root).key
}

fun min(node: Node<K, V>?): Node<K, V> {
if (node == null) throw NoSuchElementException()
var x: Node<K, V> = node
while (x.left != null) {
x = x.left!!
}
return x.key
return x
}

fun max(): K {
if (root == null) throw NoSuchElementException()
var x = root!!
return max(root).key
}

fun max(node: Node<K, V>?): Node<K, V> {
if (node == null) throw NoSuchElementException()
var x: Node<K, V> = node
while (x.right != null) {
x = x.right!!
}
return x.key
return x
}

fun pollMin() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,44 @@ class BinarySearchTreeTest {
Assert.assertTrue(tree.isEmpty())
}

@Test
fun remove() {
val tree = BinarySearchTree<Int, String>()
for (i in 0..30) {
tree.add(i, i.toString())
}
tree.remove(15)
tree.remove(0)
tree.remove(30)
Assert.assertEquals(1, tree.min())
Assert.assertEquals(29, tree.max())
tree.remove(14)
tree.remove(16)
tree.remove(1)
tree.remove(29)
Assert.assertEquals(2, tree.min())
Assert.assertEquals(28, tree.max())
tree.remove(13)
tree.remove(17)
tree.remove(2)
tree.remove(28)
Assert.assertEquals(3, tree.min())
Assert.assertEquals(27, tree.max())
tree.remove(12)
tree.remove(18)
tree.remove(3)
tree.remove(27)
Assert.assertEquals(4, tree.min())
Assert.assertEquals(26, tree.max())
tree.remove(11)
tree.remove(19)
tree.remove(4)
tree.remove(26)
Assert.assertEquals(5, tree.min())
Assert.assertEquals(25, tree.max())
Assert.assertEquals(12, tree.size())
}

@Test(expected= NoSuchElementException::class)
fun emptyMinFails() {
BinarySearchTree<Int, Unit>().min()
Expand Down

0 comments on commit f90d647

Please sign in to comment.