Red-Black Tree Deletion
Learn about the deletion function in red-black trees and all four deletion cases.
Deletion in red-black tree
Before discussing how deletion works in a Red-Black tree, let’s discuss the main difference between the insertion and deletion operations in red-black trees.
In insertion, you may violate the alternating parent-child colors property, i.e., a red parent may have a red child. But in the deletion function, you may end up deleting a black node that could violate the property: “the same number of black nodes must exist from the root to the None node for every path.”
In insertion, check the color of the sibling of the parent of the currentNode. Based on the color, perform appropriate operations to balance the tree. But, in the deletion operation, you will check the color of the sibling node of the currentNode. And based on its color, you will perform some actions to balance the tree again.
Algorithm for deletion
Here is a high-level description of the algorithm to remove the value in a red-black tree:
- Search for a node with the given value to remove. Call it currentNode.
- Remove the currentNode using the standard BST deletion operation that was studied earlier.
When deleting in a BST, you will always end up deleting either a leaf node or a node with only one child because if you want to delete an internal node, then you will always swap it with a leaf node or a node with at most one child.
- In case of the leaf node deletion, delete the node and make the child of the parent of the node to be deleted
None
. - In the case of a node with one child only, link the parent of the node to be deleted with that one child.
Name some nodes relative to node C, which is the node that you want to delete:
- Node C – The node to be deleted (let’s call it currentNode)
- Node P – The parent node of the currentNode
- Node S – The sibling node (once you rotate the tree, node R will have a sibling node, which will be named node S.)
- Node SC – The child node of node S
- Node R – The node to be replaced with the currentNode and linked with node P (node R is the single child of node C.)
Deletion cases
Study the deletion cases and the steps performed in each of these cases to make the tree balanced again. Given below is the first case in which node C or node R is red. In this type of scenario, make node R black and link it to node P.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.