fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node* Node;
  5. struct Node {
  6. int value;
  7. Node left;
  8. Node right;
  9. };
  10.  
  11. typedef struct Tree* Tree;
  12. struct Tree {
  13. Node root;
  14. };
  15.  
  16. void Tree_add(Tree tree, int value) {
  17. Node n;
  18. Node p;
  19.  
  20. n = calloc(1,sizeof(struct Node));
  21. n->value = value;
  22. n->left = NULL;
  23. n->right = NULL;
  24.  
  25. if (tree->root == NULL) {
  26. tree->root = n;
  27. } else {
  28. p = tree->root;
  29. while (1) {
  30. if (value < p->value) {
  31. if (p->left == NULL) {
  32. p->left = n;
  33. break;
  34. } else {
  35. p = p->left;
  36. }
  37. } else {
  38. if (p->right == NULL) {
  39. p->right = n;
  40. break;
  41. } else {
  42. p = p->right;
  43. }
  44. }
  45. }
  46. }
  47. }
  48.  
  49. void print_node(Node n,size_t depth){
  50. while(depth--){
  51. putchar(' ');
  52. }
  53. printf("%d\n",n->value);
  54. }
  55.  
  56. void dump_tree_impl(Node n,size_t depth){
  57. if(n){
  58. dump_tree_impl(n->right,depth + 1);
  59. print_node(n,depth);
  60. dump_tree_impl(n->left,depth + 1);
  61. }
  62. }
  63.  
  64. void free_node(Node n){
  65. if(n){
  66. free_node(n->right);
  67. free_node(n->left);
  68. free(n);
  69. }
  70. }
  71.  
  72. void free_tree(Tree t){
  73. free_node(t->root);
  74. free(t);
  75. }
  76.  
  77. void Tree_dump(Tree tree) {
  78. dump_tree_impl(tree->root,0);
  79. }
  80.  
  81. int main(void) {
  82. Tree tree = calloc(1,sizeof(struct Tree));
  83. Tree_add(tree, 3);
  84. Tree_add(tree, 1);
  85. Tree_add(tree, 5);
  86. Tree_add(tree, 0);
  87. Tree_add(tree, 2);
  88. Tree_add(tree, 4);
  89. Tree_add(tree, 6);
  90. Tree_dump(tree);
  91. free_tree(tree);
  92. return EXIT_SUCCESS;
  93. }
  94.  
  95.  
Success #stdin #stdout 0.01s 1852KB
stdin
Standard input is empty
stdout
  6
 5
  4
3
  2
 1
  0