Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  bst.c
Language: C/C++
Code:

          #include<stdio.h>
#define MAX 100




struct node
{

        int data;
        struct node *llink;
        struct node *rlink;
};
typedef struct node *treeptr;

void insert(treeptr *root, int d)
{
        if(*root==NULL)
        {
                *root=(treeptr)malloc(sizeof(struct node));
                (*root)->data=d;
                (*root)->rlink=(*root)->llink=NULL;
        return;
        }
        else if((*root)->data>d)
        {
                insert((&(*root)->llink),d);
        }
        else
        {
                insert((&(*root)->rlink),d);
        }
}
treeptr search(treeptr root,int key)
{
        if(!root)
                return NULL;
        if(key==root->data)
                return root;
        else if(key<root->data)
                return (search(root->llink,key));
        else
                return (search(root->rlink,key));
}

void inorder(treeptr root)
{
       if(root!=NULL)
        {
                inorder(root->llink);
                printf("%d ",root->data);
                inorder(root->rlink);
        }
}
void preorder(treeptr root)
{
        if(root!=NULL)
        {
                 printf("%d ",root->data);
                preorder(root->llink);
                preorder(root->rlink);
        }
}
void posorder(treeptr root)
{
        if(root!=NULL)
        {
               posorder(root->llink);

                posorder(root->rlink);
                 printf("%d ",root->data);

        }
}

int main()
{
        int ch=0,n,key,flag=0;
        treeptr root=NULL,res;

        do
        {
                printf("Menu: 1-Insert 2-inorder 3-preorder 4-postorder 5-search 6-Exit: ");
                scanf("%d",&ch);
                switch(ch)
                {
                        case 1:
                        printf("Enter element: ");
                        scanf("%d",&n);
                        insert(&root,n);
                        break;
                        case 2:
 inorder(root);
                        break;

                        case 3:preorder(root);
                                break;
                        case 4:posorder(root);
                                break;

                        case 5:printf("enter the element u want to search\n");
                                scanf("%d",&key);
                                res=search(root,key);
                                if(res)
                                        printf("element found\n");
                                else
                                        printf("element not found\n");

                                break;
                        case 6:break;
                        default:printf("Invalid Input\n");
                }
        }while(ch!=6);
}
Comments: