fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. typedef struct node {
  5. int value;
  6. struct node *left;
  7. struct node *right;
  8. } Node;
  9.  
  10. Node *
  11. newNode(int n){
  12. Node *obj;
  13. obj = (Node *)malloc(sizeof(Node));
  14. obj->value = n;
  15. obj->left = NULL;
  16. obj->right = NULL;
  17. return obj;
  18. }
  19.  
  20. Node *
  21. addNode(Node *obj, int n){
  22. if(obj == NULL){
  23. return newNode(n);
  24. }
  25.  
  26. if(obj->value == n){
  27. /*do nothing*/
  28. }else if(obj->value < n){
  29. obj->right = addNode(obj->right, n);
  30. } else{
  31. obj->left = addNode(obj->left, n);/* (6) */
  32. }
  33.  
  34. return obj;
  35. }
  36.  
  37.  
  38. Node *
  39. appendRightEnd(Node *obj, Node *right){
  40. if(obj != NULL){
  41. if(obj->right == NULL){
  42. obj->right = right;
  43. }else{
  44. obj->right = appendRightEnd(obj->right, right);/* (7) */;
  45. }
  46. }
  47. return obj;
  48. }
  49.  
  50.  
  51. Node *
  52. deleteNode(Node *obj, int n){
  53. Node *newobj;
  54.  
  55. if(obj != NULL){
  56. if(obj->value == n){
  57.  
  58. if (obj->left == NULL){
  59. newobj = obj->right;
  60. free(obj);
  61. return newobj;
  62. }else if(obj->right == NULL){
  63. newobj = obj->left;/* (8) */
  64. free(obj);
  65. return newobj;
  66. }else{
  67.  
  68. obj->left = appendRightEnd(obj->left, obj->right);
  69. newobj = obj->left;
  70. free(obj);
  71. return newobj;
  72. }
  73. }else{
  74. if(obj->value < n)
  75. obj->right = deleteNode(obj->right, n);
  76. else
  77. obj->left = deleteNode(obj->left, n);/* (9) */
  78. }
  79. }
  80. return obj;
  81. }
  82.  
  83.  
  84. void
  85. printNodes(Node *obj){
  86. if(obj != NULL){
  87. if(obj->left != NULL){
  88. printNodes(obj->left);
  89. }
  90.  
  91. printf("%d\t", obj->value);
  92.  
  93. if(obj->right != NULL){
  94. printNodes(obj->right);
  95. }
  96. }
  97.  
  98. }
  99.  
  100. int
  101. main(int argc, char *argv[]){
  102. Node *topnode = NULL;
  103.  
  104. topnode = addNode(topnode, 5);
  105. topnode = addNode(topnode, 7);
  106. topnode = addNode(topnode, 1);
  107. topnode = addNode(topnode, -1);
  108. topnode = addNode(topnode, 4);
  109. topnode = addNode(topnode, 10);
  110.  
  111. printNodes(topnode);
  112. printf("\n");
  113. topnode = deleteNode(topnode, 5);
  114.  
  115. printNodes(topnode);
  116. printf("\n");
  117. }
Runtime error #stdin #stdout 0.01s 1852KB
stdin
Standard input is empty
stdout
-1	1	4	5	7	10	
-1	1	4	7	10