0% found this document useful (0 votes)
11 views

C program to implement binary tree

This C program implements a binary tree with functions for creating nodes and performing inorder, preorder, and postorder traversals. It defines a structure for tree nodes and includes functions to insert nodes on the left and right. The main function demonstrates the creation of a simple binary tree and prints the results of the different traversal methods.

Uploaded by

babinbista1
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)
11 views

C program to implement binary tree

This C program implements a binary tree with functions for creating nodes and performing inorder, preorder, and postorder traversals. It defines a structure for tree nodes and includes functions to insert nodes on the left and right. The main function demonstrates the creation of a simple binary tree and prints the results of the different traversal methods.

Uploaded by

babinbista1
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/ 3

// C program to implement binary tree

#include <stdio.h>

#include <stdlib.h>

struct node {

int item;

struct node* left;

struct node* right;

};

// Inorder traversal

void inorderTraversal(struct node* root) {

if (root == NULL) return;

inorderTraversal(root->left);

printf("%d ->", root->item);

inorderTraversal(root->right);

// Preorder traversal

void preorderTraversal(struct node* root) {

if (root == NULL) return;

printf("%d ->", root->item);

preorderTraversal(root->left);

preorderTraversal(root->right);

// Postorder traversal

void postorderTraversal(struct node* root) {


if (root == NULL) return;

postorderTraversal(root->left);

postorderTraversal(root->right);

printf("%d ->", root->item);

// Create a new Node

struct node* createNode(int value) {

struct node* newNode = malloc(sizeof(struct node));

newNode->item = value;

newNode->left = NULL;

newNode->right = NULL;

return newNode;

// Insert on the left of the node

struct node* insertLeft(struct node* root, int value) {

root->left = createNode(value);

return root->left;

// Insert on the right of the node

struct node* insertRight(struct node* root, int value) {

root->right = createNode(value);

return root->right;

int main() {
struct node* root = createNode(1);

insertLeft(root, 2);

insertRight(root, 3);

insertLeft(root->left, 4);

printf("Inorder traversal \n");

inorderTraversal(root);

printf("\nPreorder traversal \n");

preorderTraversal(root);

printf("\nPostorder traversal \n");

postorderTraversal(root);

You might also like