0% found this document useful (0 votes)
22 views2 pages

BST Lab 10

Uploaded by

shreyadevraj874
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views2 pages

BST Lab 10

Uploaded by

shreyadevraj874
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include<stdio.

h>
#include<stdlib.h>

struct bst
{ int item;
struct bst *lptr, *rptr;
};
typedef struct bst node;

node* insert(node *root)


{ node *new1, *cur = root, *prev= NULL;
new1 = (node *) malloc(sizeof(node));
printf("\nEnter The Element ");
scanf("%d",&new1->item);
new1->lptr = new1->rptr = NULL;

if (root == NULL)
return new1;

while(cur != NULL)
{ prev = cur;
cur = new1->item < cur->item ? cur->lptr : cur->rptr;
}

if (new1->item < prev->item)


prev->lptr = new1;
else
prev->rptr = new1;
return root;
}

void inorder(node *root)


{ if (root != NULL)
{ inorder(root->lptr);
printf("%d\t", root->item);
inorder(root->rptr);
}
}

void preorder(node *root)


{ if (root != NULL)
{ printf("%d\t", root->item);
preorder(root->lptr);
preorder(root->rptr);
}
}

void postorder(node *root)


{ if (root != NULL)
{ postorder(root->lptr);
postorder(root->rptr);
printf("%d\t", root->item);
}
}

node* search(node *root, int key)


{ node *cur = root;
if(root == NULL)
return NULL;
while(cur != NULL)
{ if(key == cur->item)
return cur;
if(key < cur->item)
cur = cur->lptr;
else
cur = cur->rptr;
}
return(cur);
}

int main()
{ int choice, key,n,i;
node *root = NULL, *temp;
while(1)
{ printf("\n [Link]");
printf("\n [Link] the Tree in Pre, In and Post");
printf("\n [Link]");
printf("\n [Link]");
printf("\nEnter your choice :"); scanf("%d",&choice);
switch (choice)
{ case 1: printf("\n enter no. of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
root = insert(root); break;
case 2: if (root == NULL)
printf("Tree Is Not Created");
else
{ printf("\nThe Inorder Traversal : ");
inorder(root);
printf("\nThe Preorder Traversal: ");
preorder(root);
printf("\nThe Postorder Traversal : ");
postorder(root);
} break;
case 3: printf("\nEnter Element to be searched :");
scanf("%d",&key);
temp = search(root,key);
if(temp == NULL)
printf("Element does not exists\n");
else
printf("\nThe element %d found",temp->item);
break;
default: exit(0);
} } }

You might also like