Advertisement
Guest User

Untitled

a guest
Nov 13th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. Node* osDelete(Node* root, int i)
  2. {
  3. if (root == NULL) //key i not found
  4. return root;
  5. else
  6. {
  7. if (i < root->key)
  8. {
  9. root->left = osDelete(root->left, i);
  10. return root;
  11. }
  12. else
  13. if (i > root->key)
  14. {
  15. root->right = osDelete(root->right, i);
  16. return root;
  17. }
  18. else //key i found
  19. {
  20. if(root->left == NULL)
  21. if (root->right == NULL) //leaf
  22. {
  23. free(root);
  24. return NULL;
  25. }
  26. else //single child to the right
  27. {
  28. Node* aux = root->right;
  29. free(root);
  30. return aux;
  31. }
  32. else // we have child on left
  33. if (root->right == NULL) // single child to the left
  34. {
  35. Node* aux = root->left;
  36. free(root);
  37. return aux;
  38. }
  39. else // 2 children.
  40. {
  41. Node* predecessor = root->left;
  42. Node* parent = root;
  43. findPredecessor(&predecessor, &parent);
  44. //printf("predecessor is %d, parent is %d\n", predecessor->key, parent->key);
  45. root->key = predecessor->key;
  46. if (parent == root)
  47. {
  48. root->key = predecessor->key;
  49. root->left = predecessor->left;
  50. free(predecessor);
  51. }
  52. else
  53. {
  54. root->key = predecessor->key;
  55. parent->right = predecessor->left;
  56. free(predecessor);
  57. }
  58. return root;
  59. }
  60. }
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement