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

C Programs For Trees

This C program demonstrates how to perform insertions and traversals on a binary search tree (BST). The program allows the user to insert multiple nodes into the BST, and perform inorder, preorder and postorder traversals on the tree.

Uploaded by

reenadh sk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

C Programs For Trees

This C program demonstrates how to perform insertions and traversals on a binary search tree (BST). The program allows the user to insert multiple nodes into the BST, and perform inorder, preorder and postorder traversals on the tree.

Uploaded by

reenadh sk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

// C Program for BST-traversal

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct tree
{
int data;
struct tree *left,*right;
};
void main()
{
struct tree *root=NULL;
int option,item,n,i;
char ch;
struct tree* insertnode(struct tree*,int);
void inorder(struct tree*);
void preorder(struct tree*);
void postorder(struct tree*);
clrscr();
do
{
printf(“\n1. Create”);
printf(“\n2. Inorder Traversal”);
printf(“\n3.Preorder Traversal”);
printf(“\n4.Postorder Traversal”);
printf(“\nEnter your option(1-4):”);
scanf(“%d”,&option);
switch(option)
{
case 1: printf(“\nEnter how many
elements:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
printf(“\nEnter the item to be
inserted into BST:”);
scanf(“%d”,&item);
root=insertnode(root,item);
}
break;
case 2: printf(“\nInorder Traversal is:”);
inorder(root);
break;
case 3: printf(“\nPreorder Traversal is:”);
preorder(root);
break;
case 4: printf(“\nPostorder Traversal is :”);
postorder(root);
break;
default: printf(“\nWrong option”);
}
printf(“\nDo you wish to continue(y/n):”);
fflush(stdin);
scanf(“%c”,&ch);
}while(ch==’y’ || ch==’Y’);
getch();
}

struct tree* createnode(int item)


{
struct tree *p;
p=(struct tree*)malloc(sizeof(struct tree));
p->data=item;
p->left=NULL;
p->right=NULL;
return p;
}
struct tree* insertnode(struct tree *node,int
item)
{
struct tree* createnode(int);
if(node==NULL)
{
return createnode(item);
}
if(item<node->data)
node->left=insertnode(node->left, item);
else
node->right=insertnode(node-
>right,item);
return node;
}

void inorder(struct tree *p)


{
if(p!=NULL)
{
inorder(p->left);
printf(“%d----”,p->data);
inorder(p->right);
}
}
void preorder(struct tree *p)
{
if(p!=NULL)
{
printf(“%d----”,p->data);
preorder(p->left);
preorder(p->right);
}
}

void postorder(struct tree *p)


{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf(“%d----”,p->data);
}
}

You might also like