fork download
  1. struct node* delete(struct node* node, int target)
  2. {
  3. struct node *child = node, *parent = NULL, **branch = &node;
  4.  
  5. // Branch is a pointer to the left or right branch that we take to get to the correct node.
  6. // This information is saved so we don't have to use an if/else test to determine it later.
  7. while (child != NULL && target != child->data)
  8. {
  9. parent = child;
  10. branch = target < child->data ? &child->left
  11. : &child->right;
  12.  
  13. child = *branch;
  14. }
  15.  
  16. if (child == NULL)
  17. {
  18. return NULL;
  19. }
  20.  
  21. switch ((child->left == NULL) * 2 +
  22. (child->right == NULL))
  23. {
  24. case 3: // leaf node
  25. *branch = NULL;
  26. break;
  27. case 2: // node with right child
  28. *branch = child->right;
  29. break;
  30. case 1: // node with left child
  31. *branch = child->left;
  32. break;
  33. case 0: // node with both left and right children
  34. parent = child;
  35. child = child->right;
  36. while (child->left != NULL) {
  37. parent = child;
  38. child = child->left;
  39. }
  40. *branch->data = child->data;
  41. if (parent == *branch) {
  42. parent->right = child->right;
  43. }
  44. else {
  45. parent->left = NULL;
  46. }
  47. }
  48.  
  49. free(child);
  50. return node;
  51. }
  52.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty