NODE Insert (NODE) Void Inorder (NODE) Void Preorder (NODE) Void Postorder (NODE) NODE Search (NODE, Int) NODE Delete (NODE, Int)
NODE Insert (NODE) Void Inorder (NODE) Void Preorder (NODE) Void Postorder (NODE) NODE Search (NODE, Int) NODE Delete (NODE, Int)
#include <stdio.h>
#include <stdlib.h>
struct BST
{
int item;
struct BST *llink, *rlink;
};
NODE insert(NODE);
void inorder(NODE);
void preorder(NODE);
void postorder(NODE);
NODE search(NODE, int);
NODE Delete(NODE, int);
void main()
{
int choice, key,n,i;
NODE root = NULL, tmp, parent;
while(1)
{
printf("\n1.Create");
printf("\n2.Traverse the Tree in Preorder, Inorder, Postorder");
printf("\n3.Search");
printf("\n4.Delete an element from the Tree");
printf("\n5.Exit");
printf("\nEnter your choice :");
scanf("%d", &choice);
switch (choice)
{
case 1: printf("\n enter the number of nodes");
scanf("%d", &n);
for(i=0; i<n; i++)
root = insert(root);
break;
if (root == NULL)
return temp;
prev = NULL;
cur = root;
while(cur != NULL)
{
prev = cur;
if (item < cur-> item)
cur = cur->llink;
else
cur = cur->rlink;
}
if (item < prev->item)
prev->llink = temp;
else
prev->rlink = temp;
return root;
}
/* This function displays the tree in inorder fashion */
if (root == NULL)
{
return NULL;
}
if (data < root->item)
{ // data is in the left sub tree.
root->llink = Delete(root->llink, data);
}
else if (data > root->item)
{ // data is in the right sub tree.
root->rlink = Delete(root->rlink, data);
}
else
{
// 1: no children (leaf node)
if (root->llink == NULL && root->rlink == NULL)
{
free(root);
root = NULL;
}
// 2: one child (right)
else if (root->llink == NULL)
{
temp = root; / / save current node as a backup
root = root->rlink;
free(temp);
}
// 3: one child (left)
else if (root->rlink == NULL)
{
temp = root; // save current node as a backup
root = root->llink;
free(temp);
}
// 4: two children
else
{
min = FindMin(root->rlink); // find minimal value of right sub tree
root->item = min; // duplicate the node
root->rlink = Delete(root->rlink, min); // delete the duplicate node
}
}
return root; // parent node can update reference
}