Binary Tree Implementation in C
This PDF contains the C code for a simple Binary Tree implementation. It includes functions for
creating nodes and performing inorder, preorder, and postorder traversals.
#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the binary tree
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation error\n");
return NULL;
}
newNode->data = value;
newNode->left = newNode->right = NULL;
return newNode;
}
// Inorder Traversal (Left, Root, Right)
void inorder(struct Node* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
// Preorder Traversal (Root, Left, Right)
void preorder(struct Node* root) {
if (root == NULL) return;
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
// Postorder Traversal (Left, Right, Root)
void postorder(struct Node* root) {
if (root == NULL) return;
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
int main() {
// Creating nodes
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Inorder traversal: ");
inorder(root);
printf("\n");
printf("Preorder traversal: ");
preorder(root);
printf("\n");
printf("Postorder traversal: ");
postorder(root);
printf("\n");
return 0;
}