fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /* #define DEBUG */
  5. #if defined(DEBUG)
  6. #include "xmalloc.h"
  7. #else
  8. #define xmalloc(x, y) malloc(x)
  9. #define xfree(x, y) free(x)
  10. #define xrealloc(x, y, z) realloc(x, y)
  11. #define xmallocdump()
  12. #endif
  13.  
  14. #define ID_TREE 1001
  15. #define ID_NODE 1002
  16.  
  17. typedef struct _Node {
  18. int value;
  19. struct _Node *left;
  20. struct _Node *right;
  21. } *Node;
  22.  
  23. void Node_init(Node node, int value) {
  24. node->value = value;
  25. node->left = node->right = 0;
  26. }
  27.  
  28. Node Node_add(Node root, int value) {
  29. if (root == 0) {
  30. Node n;
  31. if ((n = xmalloc(sizeof(struct _Node), ID_NODE)) != 0) {
  32. Node_init(n, value);
  33. return n;
  34. } else {
  35. return 0;
  36. }
  37. /* changed to recursive!! */
  38. } else if (value < root->value) {
  39. root->left = Node_add(root->left, value);
  40. } else {
  41. root->right = Node_add(root->right, value);
  42. }
  43. return root;
  44. }
  45.  
  46. void Node_release(Node root) {
  47. if (root == 0)
  48. return;
  49. Node_release(root->left);
  50. Node_release(root->right);
  51. xfree(root, ID_NODE);
  52. root = 0; /* not necessary */
  53. }
  54.  
  55. /* ------------------------------------- */
  56. typedef struct _Tree {
  57. struct _Node *root;
  58. } *Tree;
  59.  
  60. void Tree_init(Tree tree) {
  61. tree->root = 0;
  62. }
  63.  
  64. void Tree_add(Tree tree, int value) {
  65. tree->root = Node_add(tree->root, value);
  66. }
  67.  
  68. void Tree_release(Tree tree) {
  69. if (tree) {
  70. Node_release(tree->root);
  71. tree->root = 0; /* to be necessary or not to be? */
  72. }
  73. }
  74.  
  75. void Tree_dump_local(Node node, int level) {
  76. int i;
  77. if (node->right)
  78. Tree_dump_local(node->right, level + 1);
  79. for (i = 0; i < level; i++) {
  80. putchar(' ');
  81. putchar(' ');
  82. }
  83. printf("%d\n", node->value);
  84. if (node->left)
  85. Tree_dump_local(node->left, level + 1);
  86. }
  87.  
  88. void Tree_dump(Tree tree) {
  89. Tree_dump_local(tree->root, 0);
  90. }
  91.  
  92. /* ------------------------------------- */
  93. int main() {
  94. Tree tree;
  95. if ((tree = xmalloc(sizeof(struct _Tree), ID_TREE)) != 0) {
  96. Tree_init(tree);
  97.  
  98. Tree_add(tree, 3);
  99. Tree_add(tree, 1);
  100. Tree_add(tree, 5);
  101. Tree_add(tree, 0);
  102. Tree_add(tree, 2);
  103. Tree_add(tree, 4);
  104. Tree_add(tree, 6);
  105.  
  106. Tree_dump(tree);
  107.  
  108. Tree_release(tree);
  109. xfree(tree, ID_TREE);
  110. }
  111. xmallocdump();
  112. return 0;
  113. }
  114. /* end */
  115.  
Success #stdin #stdout 0.01s 1808KB
stdin
Standard input is empty
stdout
    6
  5
    4
3
    2
  1
    0