Delete a nodes
| 128 | |
| 129 | // Delete a nodes |
| 130 | struct Node *deleteNode(struct Node *root, int key) |
| 131 | { |
| 132 | // Find the node and delete it |
| 133 | if (root == NULL) |
| 134 | return root; |
| 135 | |
| 136 | if (key < root->key) |
| 137 | root->left = deleteNode(root->left, key); |
| 138 | |
| 139 | else if (key > root->key) |
| 140 | root->right = deleteNode(root->right, key); |
| 141 | |
| 142 | else |
| 143 | { |
| 144 | if ((root->left == NULL) || (root->right == NULL)) |
| 145 | { |
| 146 | struct Node *temp = root->left ? root->left : root->right; |
| 147 | |
| 148 | if (temp == NULL) |
| 149 | { |
| 150 | temp = root; |
| 151 | root = NULL; |
| 152 | } |
| 153 | else |
| 154 | *root = *temp; |
| 155 | free(temp); |
| 156 | } |
| 157 | else |
| 158 | { |
| 159 | struct Node *temp = minValueNode(root->right); |
| 160 | |
| 161 | root->key = temp->key; |
| 162 | |
| 163 | root->right = deleteNode(root->right, temp->key); |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | if (root == NULL) |
| 168 | return root; |
| 169 | |
| 170 | // Update the balance factor of each node and |
| 171 | // balance the tree |
| 172 | root->height = 1 + max(height(root->left), |
| 173 | height(root->right)); |
| 174 | |
| 175 | int balance = getBalance(root); |
| 176 | if (balance > 1 && getBalance(root->left) >= 0) |
| 177 | return rightRotate(root); |
| 178 | |
| 179 | if (balance > 1 && getBalance(root->left) < 0) |
| 180 | { |
| 181 | root->left = leftRotate(root->left); |
| 182 | return rightRotate(root); |
| 183 | } |
| 184 | |
| 185 | if (balance < -1 && getBalance(root->right) <= 0) |
| 186 | return leftRotate(root); |
| 187 |
no test coverage detected