fork download
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. struct btree
  5. {
  6. int data;
  7. struct btree *leftchild;
  8. struct btree *rightchild;
  9. };
  10.  
  11.  
  12. void insert(struct btree **node, int data);
  13. void inorder(struct btree *node);
  14. void preorder(struct btree *node);
  15. void postorder(struct btree *node);
  16.  
  17.  
  18. int main()
  19. {
  20. int arr [] = {2,8,4,5,7,6,3};
  21. int index = 0;
  22.  
  23. struct btree *root = NULL, *newNode = NULL;
  24. int length = sizeof(arr)/sizeof(int);
  25.  
  26. for(index = 0; index < length; index++)
  27. {
  28. insert(&root, arr[index]);
  29. }
  30.  
  31. printf("This is the output of inorder traversal :- \n");
  32. inorder(root);
  33. printf("\n");
  34.  
  35. printf("This is the output of inorder traversal :- \n");
  36. preorder(root);
  37. printf("\n");
  38.  
  39. printf("This is the output of inorder traversal :- \n");
  40. postorder(root);
  41. printf("\n");
  42.  
  43. return 0;
  44. }
  45.  
  46. void insert(struct btree **node, int data)
  47. {
  48. if(*node == NULL)
  49. {
  50. *node = (struct btree *)malloc(sizeof(struct btree));
  51. (*node)->data = data;
  52. (*node)->leftchild = NULL;
  53. (*node)->rightchild = NULL;
  54. }
  55. else
  56. {
  57. if(data > ((*node)->data))
  58. insert(&(((*node)->rightchild)), data);
  59. else
  60. insert(&(((*node)->leftchild)), data);
  61. }
  62. }
  63.  
  64.  
  65.  
  66. void inorder(struct btree *node)
  67. {
  68. if(node != NULL)
  69. {
  70. inorder(node->leftchild);
  71. printf("%d ", node->data);
  72. inorder(node->rightchild);
  73. }
  74. }
  75.  
  76.  
  77.  
  78. void preorder(struct btree *node)
  79. {
  80. if(node != NULL)
  81. {
  82. printf("%d ", node->data);
  83. inorder(node->leftchild);
  84. inorder(node->rightchild);
  85. }
  86. }
  87.  
  88.  
  89. void postorder(struct btree *node)
  90. {
  91. if(node != NULL)
  92. {
  93. inorder(node->leftchild);
  94. inorder(node->rightchild);
  95. printf("%d ", node->data);
  96. }
  97. }
Success #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
This is the output of inorder traversal :- 
2 3 4 5 6 7 8 
This is the output of inorder traversal :- 
2 3 4 5 6 7 8 
This is the output of inorder traversal :- 
3 4 5 6 7 8 2