You are on page 1of 8

Binary search trees:

A binary tree which has the property that all elements in the left subtree of a node ‘n’
are less than the contents of ‘n’, and all elements in the right subtree of ‘n’ are greater
than or equal to the contents of n. A binary tree that has this property is called a binary
search tree.

If a binary search tree is traversed in inorder (left, root, right) and the contents of each
node are printed as the node is visited, then the numbers are printed in ascending
order.

Construct a binary search tree for the following numbers:

14,15,4,9,7,18,3,5,16,4,20,17,9,14,5

1
Binary Search tree
2
Function to insert an item into binary search tree ( avoid duplicate elements )

NODE insert (int item, NODE root)


{
NODE temp, prev, cur;
temp=getnode();
tempinfo=item;
templlink=NULL;
temprlink=NULL;
if(root==NULL)
return temp;
cur=root;
prev=NULL;
while(cur!=NULL)
{
prev=cur;
if(curinfo==item)
{ printf(“Duplicate element is %d”, curinfo);
free(temp);
return(root);
}
3
else if(item<curinfo)
{
cur=curllink;
}
else
{
cur=currlink;
}
}
if(item<previnfo)
prevllink=temp;
else
prevrllink=temp;
return root;

4
Write a C program to implement a binary search tree of integers and perform the
following traversal techniques:

i) In-order traversal
ii )Find the maximum element
iii) Search an element

Display "Duplication is not allowed" if same element is inserted again.


Display "Key element not found" if searched element is not present in the tree.
Display "Search is successful" if searched element is present in the tree.
Display "Maximum element is 15" if the maximum element is 15 in the tree.

5
Write a C function to search an element in a binary search tree.
void search ( NODE root, int item)
{
if(root==NULL)
return root;
while(root!=NULL)
{ if(rootinfo==item)
break;
if(item<rootinfo)
root=rootllink;
else
root=rootrlink;
}
if(root==NULL)
{
printf(“Element is not found or unsuccessful search”);
return root;
}
else
printf(“Successful search”);
return root;
}
6
Write a C function to find maximum value in a Binary search
tree:

void max(NODE root)


{
NODE cur;
if(root==NULL)
return root;
cur=root;

while(currlink!=NULL)
{
cur=currlink;
}
printf(“Maximum element=%d”, curinfo);
}
}

7
Write a C function to count the number of nodes in BST
int count_Node(Node root)
{
if(root!=NULL)
{
count_Node(rootleft);
count++;
count_Node(rootright);
return count;
}
Write a C function to count the number of leaf nodes:
int count_Leaf(Node root)
{
if(root!=NULL)
{
count_Leaf(rootleft);
if((rootleft==NULL) && (rootright==NULL))
count++;
count_Leaf(rootright);
}
return count;
8
}

You might also like