Binary Search Tree: Part 2 min, floor, delete. Algorithms Series
An important feature of Binary Search Tree (BST) is that it allows keeping keys in order. So we are able to apply wide range of operations that involves relative key order.
In this article we will take a look at some of them.
As in the previous part we will use TDD to ensure algorithm correctness.
MIN
min() method should return the smallest key.
The implementation of MIN key is quite simple, we need to go left recursively until left node is null.
The implementation of MAX key will be the same, only we need to go recursively right.
Floor and ceiling
floor() method should return the largest key less than or equal to given key.
ceiling() method should return smallest key grater than or equal to given key.
Test cases for floor() should check:
- that floor of an existing key in BST returns same key
- that floor returns the largest key that less than given key
In the implementation we compare given key to the key of a Node to find Subtree first, and then key that smaller or equals to the key.
ceiling() implementation will be the same as floor() with right, left and <, > interchanged.
DELETE
Deletion in the BST can seem tricky, when you do not stare at those trees few days in a row. First, we need to implement deleteMit() method. So it can be reused later in deletion.
Test case should check that there is no key present after deletion.
To delete element with a minimal key we need to go through next steps:
- find the minimal node - go left until left node is null
- remove it - replace node to be deleted with the child right node
- update node number
With the deleteMin() in place we can proceed with delete.
Test cases for delete() should check:
- that there is no key present
- that successor of deleted element is correct
So, we need next steps to implement deletion:
- find the node by comparing the key
- if node to delete has only one child, we simply replace it with a child node
- save the node to be deleted
- get the successor, which is minimal value of the right subtree min(node.right)
- apply deleteMin() because we need to replace successor’s node (left node) with the right node in this subtree
- left link of the successor will be the left node to be deleted
Complete implementation with test cases can be found on GitHub.
Sources: