Idea
This brings me back to my university time when we were forced to manually implement heap……
However, this one is simpler but still, not an easy task to do.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
The searching part is easy, let’s skip it.
How do we delete a node?
- trivial case: the node is a leaf node, just delete it.
- if the node to be deleted has a right subtree, find the successor, swap them and delete the node again (recursively) in the right subtree.
- if the node does not have a right subtree, find the predecessor, swap them and delete the node again (recursively) in the left subtree.
One thing that confused me a little bit is: why can we do 2 and 3?
You can try to flatten the tree and the answer is obvious (by flatten I mean in-order traversal), the predecessor and the successor are next to the node to be deleted, so swap them will not break the BST property for the subtree (the original BST is broken but eventually we will delete the node, so the original BST will be ok eventually).
Algorithm
To find successor, go right once and keep going left.
|
|
To find predecessor, go left once and keep going right.
|
|
With these and simple recursion, we can solve the problem.
|
|