Binary Tree Traversal

    
      #include <stdio.h>
      #include <stdlib.h>

      struct Node {
          int data;
          struct Node* left;
          struct Node* right;
      };

      struct Node* createNode(int data) {
          struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
          if (newNode == NULL) {
              printf("Memory allocation failed.\\n");
              exit(EXIT_FAILURE);
          }

          newNode->data = data;
          newNode->left = NULL;
          newNode->right = NULL;

          return newNode;
      }

      struct Node* constructBinaryTree() {
          struct Node* root = createNode(1);
          root->left = createNode(2);
          root->right = createNode(3);
          root->left->left = createNode(4);
          root->left->right = createNode(5);

          return root;
      }

      void inorderTraversal(struct Node* root) {
          if (root != NULL) {
              inorderTraversal(root->left);
              printf("%d ", root->data);
              inorderTraversal(root->right);
          }
      }

      void preorderTraversal(struct Node* root) {
          if (root != NULL) {
              printf("%d ", root->data);
              preorderTraversal(root->left);
              preorderTraversal(root->right);
          }
      }

      void postorderTraversal(struct Node* root) {
          if (root != NULL) {
              postorderTraversal(root->left);
              postorderTraversal(root->right);
              printf("%d ", root->data);
          }
      }

      int main() {
          struct Node* root = constructBinaryTree();

          printf("Inorder Traversal: ");
          inorderTraversal(root);
          printf("\\n");

          printf("Preorder Traversal: ");
          preorderTraversal(root);
          printf("\\n");

          printf("Postorder Traversal: ");
          postorderTraversal(root);
          printf("\\n");

          return 0;
      }