Deleting a node
| 56 | |
| 57 | // Deleting a node |
| 58 | struct node *deleteNode(struct node *root, int key) { |
| 59 | // Return if the tree is empty |
| 60 | if (root == NULL) return root; |
| 61 | |
| 62 | // Find the node to be deleted |
| 63 | if (key < root->key) |
| 64 | root->left = deleteNode(root->left, key); |
| 65 | else if (key > root->key) |
| 66 | root->right = deleteNode(root->right, key); |
| 67 | else { |
| 68 | // If the node is with only one child or no child |
| 69 | if (root->left == NULL) { |
| 70 | struct node *temp = root->right; |
| 71 | free(root); |
| 72 | return temp; |
| 73 | } else if (root->right == NULL) { |
| 74 | struct node *temp = root->left; |
| 75 | free(root); |
| 76 | return temp; |
| 77 | } |
| 78 | |
| 79 | // If the node has two children |
| 80 | struct node *temp = minValueNode(root->right); |
| 81 | |
| 82 | // Place the inorder successor in position of the node to be deleted |
| 83 | root->key = temp->key; |
| 84 | |
| 85 | // Delete the inorder successor |
| 86 | root->right = deleteNode(root->right, temp->key); |
| 87 | } |
| 88 | return root; |
| 89 | } |
| 90 | |
| 91 | // Driver code |
| 92 | int main() { |