Node to be deleted is leaf: Simply remove from the tree.
Node to be deleted has only one child: Copy the child to the node and delete the child.
Node to be deleted has two children: Find inorder successor of the node. Copy contents of the inorder successor to the node and delete the inorder successor. Note that inorder predecessor can also be used.
The important thing to note is: Inorder successor is needed only when right child is not empty.
Also, I learned from the visualization algorithm websiteLINK.
1 2 3 4 5 6 7 8
search for v if v is a leaf delete leaf v else if v has 1 child bypass v else replace v with successor
It is worth noting that when you delete nodes in a tree, deletion process will be in post-order. That is to say, when you delete a node, you will delete its left child and its right child before you delete the node itself.
if(key < root->key) root->left = deleteNode(root->left, key); elseif(key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, then this is the node // to be deleted else{ // 1. node with only one child or no child if(root->left == NULL){ struct node* temp = root->right; free(root); return temp; } elseif(root->right == NULL){ struct node* temp = root->left; free(root); return temp; } // 2. node with 2 children: Get the inorder successor(smallest in the right subtree) structnode* temp =minValueNode(root->right); root->key = temp->key; root->right = deleteNode(root->right, temp->key); } return root; }