Binary Search Tree is very important data structure in computer science. I am trying to cover most of it in the article. You should be able to answer following questions after reading (and understanding) the article.
- What is Binary Search Tree?
- Why Binary Search Tree is used for?
- How to insert a node in a Binary Search Tree?
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
Structure of Binary Search Tree Node:
struct tnode {
int data;
struct tnode *left;
struct tnode *right;
};
Data is an integer, which will contain the actual data and left and right are again the Binary Search Tree nodes containing left and right subtrees.
How to insert a Node in Binary Search Tree:
While inserting a new node to binary search tree, we need to maintain the basic property of Binary Search Tree . Traverse through the tree and find out the correct position for the given node.
struct tnode *insert(struct tnode *p , int val){
if(p==NULL){
p = (struct tnode *)malloc(sizeof(struct tnode));
p->data = val;
p->left = NULL;
p->right = NULL;
}else{
struct tnode *q,*temp;
q=p;
temp=p;
while(q != NULL ){
temp= q;
if( val >= temp->data)
q=temp->right;
else
q=temp->left;
}
struct tnode *n;
n= (struct tnode *)malloc (sizeof(struct tnode));
n->data =val;
if( val >=temp->data )
temp->right =n;
else
temp->left = n;
}
return p;
}




