Binary Search
Binary Search
if(item == cur->info)
break;
parent = cur;
cur = (item < cur->info) ? cur->llink : cur->rlink;
}
if( cur == NULL)
{
cout<<"Item not found\n";
return root;
}
if(cur->llink == NULL)
q = cur->rlink;
else if(cur->rlink == NULL)
q = cur->llink;
else
{
suc = cur->rlink;
while(suc->llink != NULL)
suc = suc->llink;
suc->llink = cur->llink;
q = cur->rlink;
}
if(parent == NULL)
return q;
if(cur == parent->llink)
parent->llink = q;
else
parent->rlink = q;
return root;
}
void BST::search(NODE root)
{
int key,flag=0;
if(root == NULL)
{
cout<<"\n tree is empty";
return;
}
cout<<"\nenter the key::";
cin>>key;
while(root!=NULL)
{
if(key==root->info)
{
flag=1;
cout<<"\n element is found";
break;
}
else if(key<root->info)
root=root->llink;
else
root=root->rlink;
}
if(flag==0)
cout<<"\n element is not found";
}
int main()
{
NODE root = NULL;
int choice,item;
BST obj;
for(;;)
{
cout<<"\n\n1.Insert 2.Preorder 3.Inorder 4.Postorder 5.delete 6.Search
7.Exit \n";
cout<<"\nEnter your choice::";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\nEnter the item to be inserted::";
cin>>item;
root = obj.insert(item,root);
break;
case 2:
if(root == NULL)
cout<<"\nTree is empty\n";
else
{
cout<<"\nThe given Tree is \n";
obj.display(root,1);
cout<<"\nPreorder Treaversal is \n";
obj.preorder(root);
cout<<"\n";
}
break;
case 3:
if(root == NULL)
cout<<"\nTree is empty\n";
else
{
cout<<"\nThe given Tree is \n";
obj.display(root,1);
cout<<"\nInorder Treaversal is \n";
obj.inorder(root);
cout<<"\n";
}
break;
case 4:
if(root == NULL)
cout<<"\nTree is empty\n";
else
{
cout<<"\nThe given Tree is \n";
obj.display(root,1);
cout<<"\nPostorder Treaversal is \n";
obj.postorder(root);
cout<<"\n";
}
break;
case 5:
cout<<"\nEnter the item to be deleted\n";
cin>>item;
root =obj.delete_item(item,root);
break;
case 6:
cout<<"\nThe given Tree is \n";
obj.display(root,1);
obj.search(root);
break;
case 7: exit(0) ;
default : cout<<"\n invalid choice";
}
}
return 0;
}