Unit 3b
Unit 3b
The value at N is greater than every value in the left subtree of N and
The value at N is less than every value in the right subtree of N.
The reason why we go for a Binary Search tree is to improve the searching
efficiency.
The average case time complexity of the search operation in a binary search tree
is O( log n ).
6
2 8
1 4
Empty
empty (T)
{
if (T!=NULL)
{
empty(T->left);
empty(T->right);
free(T);
}
return(NULL);
}
2 8
1 4
2 8
1 4
Delete Node 3
3
Case 2 : NODE HAS 1 CHILD
6 6
2 8
2 8
1 4
1 3
Fig :- Indicates Deletion of a node(4) with one child before and after.
Replace the key of that node with the minimum element at the right subtree
Delete the minimum element
o Has either no child or only right child because if it has a left child that left
child would be smaller and would have been chosen.
o So Invoke Case 1 Or 2.
6
6 6
2 8 3 8
3 8
1 5 1 5
1 5
3 3
4
4
4
Fig :- Deletion of a node (2) with two children before and After.
delete(T,x)
{
if(T==NULL)
{
printf(“Element Not Found”):
exit(1);
}
else
{
if(x<T->info)
T->left=delete(x,T->left);
else
if(x>T->info)
T->right=delete(x,T->right);
else
if(T->left && T->right)
{
temp = findmin(T->right);
T->element = temp->element;
T->right = delete(T->element,T->right);
}
else
{
temp = T;
if(T->left= =NULL)
T=T->right;
There are three standard ways of traversing a binary tree T with root R. They are:
( i ) Preorder Traversal
(ii ) Inorder Traversal
(iii) Postorder Traversal
Preorder Traversal:
Inorder Traversal:
Postorder Traversal:
a. Preorder Traversal
PREORDER( Root )
Nodeptr Root;
{
if( Root!=NULL )
{
printf info( Root )
preorder( left(Root))
preorder ( right(Root))
}
}
b. Inorder Traversal
INORDER( Root )
Nodeptr Root;
{
if( Root!=NULL )
{
inorder( left(Root))
printf info( Root )
inorder ( right(Root))
}
}
c. Postorder Traversal
POSTORDER( Root )
Nodeptr Root;
{
if( Root!=NULL )
{
postorder( left(Root))
postorder ( right(Root))
printf info( Root )
}
}