Pages

Thursday, April 3, 2014

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("
Enter the data ");
        scanf("%d",&element);
        temp=nodecreate(element);
        *node=temp;
    }
    printf("
Do 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("
Do 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("
Enter y/Y for creating tree ");
fflush(stdin);
scanf("%c",&ch);
if(ch==y||ch==Y)
{
    maketree(&root);
    printf("
The preorder traversal is
");
    preorder(root);
    printf("
The postorder traversal is
");
    postorder(root);
    printf("
The inorder traversal is
");
    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. Thanks.. :)

Related Posts by Categories

0 comments:

Post a Comment