fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // Define a node structure
  5. struct Node {
  6. int data;
  7. struct Node* left;
  8. struct Node* right;
  9. };
  10.  
  11. // Function to create a new node
  12. struct Node* createNode(int data) {
  13. struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  14. newNode->data = data;
  15. newNode->left = NULL;
  16. newNode->right = NULL;
  17. return newNode;
  18. }
  19.  
  20. // Function to insert nodes (for simplicity, as a Binary Search Tree)
  21. struct Node* insertNode(struct Node* root, int data) {
  22. if (root == NULL) {
  23. return createNode(data);
  24. }
  25.  
  26. if (data < root->data) {
  27. root->left = insertNode(root->left, data);
  28. } else {
  29. root->right = insertNode(root->right, data);
  30. }
  31.  
  32. return root;
  33. }
  34.  
  35. // Inorder Traversal (Left, Root, Right)
  36. void inorderTraversal(struct Node* root) {
  37. if (root != NULL) {
  38. inorderTraversal(root->left);
  39. printf("%d ", root->data);
  40. inorderTraversal(root->right);
  41. }
  42. }
  43.  
  44. // Preorder Traversal (Root, Left, Right)
  45. void preorderTraversal(struct Node* root) {
  46. if (root != NULL) {
  47. printf("%d ", root->data);
  48. preorderTraversal(root->left);
  49. preorderTraversal(root->right);
  50. }
  51. }
  52.  
  53. // Postorder Traversal (Left, Right, Root)
  54. void postorderTraversal(struct Node* root) {
  55. if (root != NULL) {
  56. postorderTraversal(root->left);
  57. postorderTraversal(root->right);
  58. printf("%d ", root->data);
  59. }
  60. }
  61.  
  62. // Main function to demonstrate binary tree
  63. int main() {
  64. struct Node* root = NULL;
  65. int values[] = {50, 30, 20, 40, 70, 60, 80};
  66. int n = sizeof(values) / sizeof(values[0]);
  67.  
  68. // Insert nodes
  69. for (int i = 0; i < n; i++) {
  70. root = insertNode(root, values[i]);
  71. }
  72.  
  73. // Display traversals
  74. printf("Inorder Traversal: ");
  75. inorderTraversal(root);
  76. printf("\n");
  77.  
  78. printf("Preorder Traversal: ");
  79. preorderTraversal(root);
  80. printf("\n");
  81.  
  82. printf("Postorder Traversal: ");
  83. postorderTraversal(root);
  84. printf("\n");
  85.  
  86. return 0;
  87. }
  88.  
  89.  
Success #stdin #stdout 0.01s 5300KB
stdin
45
stdout
Inorder Traversal: 20 30 40 50 60 70 80 
Preorder Traversal: 50 30 20 40 70 60 80 
Postorder Traversal: 20 40 30 60 80 70 50