9.binary Search Tree - Set 1 (Search and Insertion) : Searching A Key
9.binary Search Tree - Set 1 (Search and Insertion) : Searching A Key
The above properties of Binary Search Tree provide an ordering among keys so that the operations like
search, minimum and maximum can be done fast. If there is no ordering, then we may have to compare
every key to search a given key.
Searching a Key
To search a given key in Binary Search Tree, we first compare it with root, if the key is present at root, we
return root. If key is greater than root’s key, we recur for right subtree of root node. Otherwise we recur for
left subtree.
Insertion of a key
A new key is always inserted at leaf. We start searching a key from root till we hit a leaf
node. Once a leaf node is found, the new node is added as a child of the leaf node.
100 100
/ \ Insert 40 / \
/ \ / \
10 30 10 30
\
40
Program:
#include <stdio.h>
#include <stdlib.h>
struct btnode
int value;
void delete1();
void insert();
void delete();
void create();
int flag = 1;
void main()
int ch;
printf("\nOPERATIONS ---");
printf("6 - Exit\n");
while(1)
scanf("%d", &ch);
switch (ch)
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
inorder(root);
break;
case 4:
preorder(root);
break;
case 5:
postorder(root);
break;
case 6:
exit(0);
default :
break;
void insert()
create();
if (root == NULL)
root = temp;
else
search(root);
/* To create a node */
void create()
int data;
scanf("%d", &data);
temp->value = data;
if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert at right */
search(t->r);
t->r = temp;
else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at left */
search(t->l);
t->l = temp;
if (root == NULL)
return;
if (t->l != NULL)
inorder(t->l);
if (t->r != NULL)
inorder(t->r);
void delete()
{
int data;
if (root == NULL)
return;
scanf("%d", &data);
t1 = root;
t2 = root;
search1(root, data);
if (root == NULL)
return;
if (t->l != NULL)
preorder(t->l);
if (t->r != NULL)
preorder(t->r);
if (root == NULL)
return;
if (t->l != NULL)
postorder(t->l);
if (t->r != NULL)
postorder(t->r);
if ((data>t->value))
t1 = t;
search1(t->r, data);
t1 = t;
search1(t->l, data);
else if ((data==t->value))
delete1(t);
}
/* To delete a node */
int k;
if (t1->l == t)
t1->l = NULL;
else
t1->r = NULL;
t = NULL;
free(t);
return;
if (t1 == t)
root = t->l;
t1 = root;
else if (t1->l == t)
t1->l = t->l;
else
t1->r = t->l;
t = NULL;
free(t);
return;
if (t1 == t)
root = t->r;
t1 = root;
else if (t1->r == t)
t1->r = t->r;
else
t1->l = t->r;
t == NULL;
free(t);
return;
t2 = root;
if (t->r != NULL)
k = smallest(t->r);
flag = 1;
else
k =largest(t->l);
flag = 2;
search1(root, k);
t->value = k;
t2 = t;
if (t->l != NULL)
t2 = t;
return(smallest(t->l));
else
return (t->value);
if (t->r != NULL)
t2 = t;
return(largest(t->r));
else
return(t->value);