Guest User

Untitled

a guest
Jan 16th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. Node* BinarySearchTree::deleteKey(Node *root, int key) {
  2. if (!root) return root;
  3.  
  4. if (key < root->val) {
  5. // If the key to be deleted is smaller than the root's key, then it lies in left subtree
  6. root->left = deleteKey(root->left, key);
  7. } else if (key > root->val) {
  8. // If the key to be deleted is greater than the root's key, then it lies in right subtree
  9. root->right = deleteKey(root->right, key);
  10. } else {
  11. // Node with only one child or no child
  12. if (!root->left) {
  13. Node *temp = root->right;
  14. free(root);
  15. return temp;
  16. } else if (!root->right) {
  17. Node *temp = root->left;
  18. free(root);
  19. return temp;
  20. }
  21.  
  22. // Node with two children: get the inorder successor
  23. Node *temp = minNode(root->right);
  24.  
  25. // Copy the inorder successor's content to this node
  26. root->val = temp->val;
  27.  
  28. // Delete the inorder successor
  29. root->right = deleteKey(root->right, temp->val);
  30. }
  31.  
  32. return root;
  33. }
Add Comment
Please, Sign In to add comment