Search Tutorials

Saturday 20 April 2013

C code to implement Binary Tree

//C program to implement binary Tree//

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct tree
{
    int data;
    struct tree *left,*right;
};
struct tree *nodecreate(int item)
{
     struct tree *t;
     t=(struct tree*)malloc(sizeof(struct tree));
     t->data=item;
     t->left=NULL;
     t->right=NULL;
     return(t);
}
void maketree(struct tree **node)
{
    char c;
    int element;
    struct tree *temp;
    if(*node==NULL)
    {
        printf("\nEnter the data ");
        scanf("%d",&element);
        temp=nodecreate(element);
        *node=temp;
    }
    printf("\nDo u want to create left child of %d (y/Y) ",(*node)->data);
    fflush(stdin);
    scanf("%c",&c);
    if(c=='y'||c=='Y')
        maketree(&(*node)->left);
    printf("\nDo u want to create right child of %d (y/Y) ",(*node)->data);
    fflush(stdin);
    scanf("%c",&c);
    if(c=='y'||c=='Y')
        maketree(&(*node)->right);
}
void preorder(struct tree *node)
{
    if(node!=NULL)
    {
    printf("%d ",node->data);
    preorder(node->left);
    preorder(node->right);
    }
}
void inorder(struct tree *node)
{
    if(node!=NULL)
    {
    inorder(node->left);
    printf("%d ",node->data);
    inorder(node->right);
    }
}
void postorder(struct tree *node)
{
    if(node!=NULL)
    {
    postorder(node->left);
    postorder(node->right);
    printf("%d ",node->data);
  //printf("%d ",node->data);
    }
}
void main()
{
struct tree *root;
char ch;
clrscr();
root=NULL;
printf("\nEnter y/Y for creating tree ");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
{
    maketree(&root);
    printf("\nThe preorder traversal is\n");
    preorder(root);
    printf("\nThe postorder traversal is\n");
    postorder(root);
    printf("\nThe inorder traversal is\n");
    inorder(root);
}
getch();
}

/* Output of Binary Tree program */

C code to implement Binary Tree
Output of Binary Tree Program

C code to implement Binary Tree
Output of Binary Tree Program

For more related to Data Structure see List of Data Structure Programs. If you like this program, Please share and comment to improve this blog.

No comments:

Post a Comment

Back to Top