Binary Search Tree
Binary Search Tree
In a binary tree, every node can have a maximum of two children but there is no need to
maintain the order of nodes basing on their values. In a binary tree, the elements are arranged
in the order they arrive at the tree from top to bottom and left to right.
To enhance the performance of binary tree, we use a special type of binary tree known as
Binary Search Tree. Binary search tree mainly focuses on the search operation in a binary
tree. Binary search tree can be defined as follows...
Binary Search Tree is a binary tree in which every node contains only smaller values in its
left subtree and only larger values in its right subtree.
In a binary search tree, all the nodes in the left subtree of any node contains smaller values
and all the nodes in the right subtree of any node contains larger values as shown in the
following figure...
Example
The following tree is a Binary Search Tree. In this tree, left subtree of every node contains
nodes with smaller values and right subtree of every node contains larger values.
Every binary search tree is a binary tree but every binary tree need not to be binary
search tree.
1. Search
2. Insertion
3. Deletion
Step 1 - Create a newNode with given value and set its left and right to NULL.
Step 2 - Check whether tree is Empty.
Step 3 - If the tree is Empty, then set root to newNode.
Step 4 - If the tree is Not Empty, then check whether the value of newNode is
smaller or larger than the node (here it is root node).
Step 5 - If newNode is smaller than or equal to the node then move to its left child. If
newNode is larger than the node then move to its right child.
Step 6- Repeat the above steps until we reach to the leaf node (i.e., reaches to NULL).
Step 7 - After reaching the leaf node, insert the newNode as left child if the newNode
is smaller or equal to that leaf node or else insert it as right child.
Example
10,12,5,4,20,8,7,15 and 13
struct node
{
int data;
struct node *left;
struct node *right;
};
int main()
{
int n , i;
struct node *p , *q , *root;
printf("Enter the number of nodes to be insert: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p = (struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->left = NULL;
p->right = NULL;
if(i == 0)
{
root = p; // root always point to the root node
}
else
{
q = root; // q is used to traverse the tree
while(1)
{
if(p->data > q->data)
{
if(q->right == NULL)
{
q->right = p;
break;
}
else
q = q->right;
}
else
{
if(q->left == NULL)
{
q->left = p;
break;
}
else
q = q->left;
}
}
}
return 0;
}
Output