Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. bool remove(node* temp, int val) {
  2. if (temp == NULL) return false;
  3. node* parent = NULL;
  4. while (temp->data != val) {
  5. if (temp == NULL) return false;
  6. if (val = temp->data) continue;
  7. parent = temp;
  8. if (val > temp->data) temp = temp->right;
  9. if (val < temp->data) temp = temp->left;
  10. }
  11.  
  12. //In case it has no child
  13. if ((temp->right == NULL) && (temp->left == NULL)) delete temp;
  14.  
  15. //Only left child is present
  16. if ((temp->right == NULL)) {
  17. if (parent == NULL) head = temp->left;
  18. else {
  19. if (parent->data > temp->left->data) parent->left = temp->left;
  20. else parent->right = temp->left;
  21. }
  22. delete temp;
  23. }
  24.  
  25. //Only right child is present
  26. if ((temp->left == NULL)) {
  27. if (parent == NULL) head = temp->right;
  28. else {
  29. if (parent->data > temp->right->data) parent->left = temp->right;
  30. else parent->right = temp->right;
  31. }
  32. delete temp;
  33. }
  34.  
  35. //In case it has two children
  36. if ((temp->right != NULL) && (temp->left != NULL)) {
  37. node* inorder_successor = getInOrderSuccessor(temp->right);
  38. temp->data = inorder_successor->data;
  39. remove(head,inorder_successor->data);
  40. }
  41. no_of_elements--;
  42. }
  43.  
  44. node* getInOrderSuccessor(node* temp) {
  45. if(temp->left!=NULL)
  46. return getInOrderSuccessor(temp->left);
  47. return temp;
  48. }
  49.  
  50. BST *tree = new BST();
  51. bool temp = tree->remove(tree->head,key);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement