fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. typedef struct tree {
  5. int data;
  6. struct tree *right;
  7. struct tree *left;
  8. } tree;
  9.  
  10. void inorder_tree(tree *root);
  11. void preorder_tree(tree *root);
  12. void postorder_tree(tree *root);
  13. tree *insert_tree(tree *root, int data);
  14.  
  15. int main(void)
  16. {
  17. int i;
  18. int a[5];
  19. for (i = 0; i < 5; i++)
  20. scanf("%d", &a[i]);
  21. tree *root = NULL;
  22. for (i = 0; i < 5; i++)
  23. root = insert_tree(root, a[i]);
  24. printf("inorder\n");
  25. inorder_tree(root);
  26. printf("preorder\n");
  27. preorder_tree(root);
  28. printf("postorder\n");
  29. postorder_tree(root);
  30. return 0;
  31. }
  32. void inorder_tree(tree *root)
  33. {
  34. if (root == NULL)
  35. return;
  36. inorder_tree(root->left);
  37. printf("%d\n", root->data);
  38. inorder_tree(root->right);
  39. return;
  40. }
  41. void preorder_tree(tree *root)
  42. {
  43. if (root == NULL)
  44. return;
  45. printf("%d\n", root->data);
  46. preorder_tree(root->left);
  47. preorder_tree(root->right);
  48. return;
  49. }
  50. void postorder_tree(tree *root)
  51. {
  52. if (root == NULL)
  53. return;
  54. postorder_tree(root->left);
  55. postorder_tree(root->right);
  56. printf("%d\n", root->data);
  57. return;
  58. }
  59. tree *insert_tree(tree *root, int data)
  60. {
  61. tree *current;
  62. current = (tree *)malloc(sizeof(tree));
  63. assert(current != NULL);
  64. current->data = data;
  65. if (root == NULL) {
  66. current->right = NULL;
  67. current->left = NULL;
  68. return (current);
  69. }
  70. if (data < root->data)
  71. root->left = insert_tree(root->left, data);
  72. else
  73. root->right = insert_tree(root->right, data);
  74. return (root);
  75. }
Success #stdin #stdout 0s 4532KB
stdin
4 6 2 9 5
stdout
inorder
2
4
5
6
9
preorder
4
2
6
5
9
postorder
2
5
9
6
4