0% found this document useful (0 votes)
5 views2 pages

Binary Tree C Code

This document provides a C implementation of a simple Binary Tree, including functions for creating nodes and performing various tree traversals: inorder, preorder, and postorder. It includes the necessary code structures and functions to facilitate these operations. The main function demonstrates the creation of a binary tree and displays the results of the traversals.

Uploaded by

24030164
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Binary Tree C Code

This document provides a C implementation of a simple Binary Tree, including functions for creating nodes and performing various tree traversals: inorder, preorder, and postorder. It includes the necessary code structures and functions to facilitate these operations. The main function demonstrates the creation of a binary tree and displays the results of the traversals.

Uploaded by

24030164
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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;
}

You might also like