fork download
  1. #include <bits/stdc++.h>
  2.  
  3. /*
  4.  Tree General
  5. + preorder
  6. + postorder
  7. + inorder traversal dosenot have a natural definition, because there is no
  8. particular number of children for an internal node
  9. */
  10.  
  11.  
  12. typedef struct node {
  13. int data;
  14. struct node *left_most_child;
  15. struct node *right_subling;
  16. }node;
  17.  
  18. node* create_node(int data) {
  19. node *root = (node*)malloc(sizeof(node));
  20. root->data = data;
  21. root->left_most_child = NULL;
  22. root->right_subling = NULL;
  23. return root;
  24. }
  25.  
  26. node* create_tree() {
  27. node *a = create_node('A');
  28. node *b = create_node('B');
  29. node *c = create_node('C');
  30. node *d = create_node('D');
  31. node *e = create_node('E');
  32. node *f = create_node('F');
  33. node *g = create_node('G');
  34. node *h = create_node('H');
  35. node *i = create_node('I');
  36. node *j = create_node('J');
  37.  
  38. // link notes
  39.  
  40. a->left_most_child = b;
  41. b->right_subling = c;
  42. c->right_subling = d;
  43.  
  44. c->left_most_child = e;
  45. e->right_subling = f;
  46.  
  47. d->left_most_child = g;
  48.  
  49. e->left_most_child = h;
  50. h->right_subling = i;
  51.  
  52. f->left_most_child = j;
  53.  
  54. return a;
  55. }
  56.  
  57.  
  58. void preOrder(node *root) {
  59. if(root != NULL) {
  60. printf("%c ",root->data);
  61. preOrder(root->left_most_child);
  62. preOrder(root->right_subling);
  63. }
  64.  
  65. }
  66. // chua nghi ra, cach duoi chi ap dung voi cay nhi phan.
  67.  
  68. //void inOrder(node *root) {
  69. // if(root != NULL) {
  70. // inOrder(root->left_most_child);
  71. // printf("%c ",root->data);
  72. // inOrder(root->right_subling);
  73. // }
  74. //
  75. //}
  76.  
  77. void postOrder(node *root) {
  78. if(root != NULL) {
  79. postOrder(root->left_most_child);
  80. postOrder(root->right_subling);
  81. printf("%c ",root->data);
  82. }
  83. }
  84.  
  85. void free_tree(node *root) {
  86. if (root == NULL) {
  87. return;
  88. }
  89. free_tree(root->left_most_child);
  90. free_tree(root->right_subling);
  91. free(root);
  92. }
  93. int main() {
  94. node *root = create_tree();
  95. printf("Thu tu truoc\n");
  96. preOrder(root);
  97. // printf("\n");
  98. // printf("Thu tu giua\n");
  99. // inOrder(root);
  100. printf("\n");
  101. printf("Thu tu sau\n");
  102. postOrder(root);
  103. free_tree(root);
  104. }
Success #stdin #stdout 0s 4396KB
stdin
Standard input is empty
stdout
Thu tu truoc
A  B  C  E  H  I  F  J  D  G  
Thu tu sau
I  H  J  F  E  G  D  C  B  A