Binary Search Tree is a node-based binary tree data structure which has the following properties:
- The left subtree of a node contains only nodes with keys lesser than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- The left and right subtree each must also be a binary search tree.
- Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets, multisets, and associative arrays.
- When inserting or searching for an element in a binary search tree, the key of each visited node has to be compared with the key of the element to be inserted or found.
Basic Operations
Following are the basic operations of a tree −
-
Search − Searches an element in a tree.
-
Insert − Inserts an element in a tree.
-
Pre-order Traversal − Traverses a tree in a pre-order manner.
-
In-order Traversal − Traverses a tree in an in-order manner.
-
Post-order Traversal − Traverses a tree in a post-order manner.
algorithm of binary search tree:
struct node* search(int data){
struct node *current = root;
printf("Visiting elements: ");
while(current->data != data){
if(current != NULL) {
printf("%d ",current->data);
if(current->data > data){
current = current->leftChild;
}
else {
current = current->rightChild;
}
if(current == NULL){
return NULL;
}
}
}
return current;
}