Binary Search Tree
Binary Search Tree
A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties −
The left sub-tree of a node has a key less than or equal to its parent node's key.
The right sub-tree of a node has a key greater than to its parent node's key.
Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree and can be
defined as −
Representation
BST is a collection of nodes arranged in a way where they maintain BST properties. Each node has a key
and an associated value. While searching, the desired key is compared to the keys in BST and if found,
the associated value is retrieved.
We observe that the root node key (27) has all less-valued keys on the left sub-tree and the higher valued
keys on the right sub-tree.
Basic Operations
https://www.tutorialspoint.com/data_structures_algorithms/binary_search_tree.htm 1/3
3/20/2020 Data Structure - Binary Search Tree - Tutorialspoint
Node
Define a node having some data, references to its left and right child nodes.
struct node {
int data;
struct node *leftChild;
struct node *rightChild;
};
Search Operation
Whenever an element is to be searched, start searching from the root node. Then if the data is less than
the key value, search for the element in the left subtree. Otherwise, search for the element in the right
subtree. Follow the same algorithm for each node.
Algorithm
while(current->data != data){
if(current != NULL) {
printf("%d ",current->data);
//not found
if(current == NULL){
return NULL;
}
}
}
return current;
}
Insert Operation
https://www.tutorialspoint.com/data_structures_algorithms/binary_search_tree.htm 2/3
3/20/2020 Data Structure - Binary Search Tree - Tutorialspoint
Whenever an element is to be inserted, first locate its proper location. Start searching from the root node,
then if the data is less than the key value, search for the empty location in the left subtree and insert the
data. Otherwise, search for the empty location in the right subtree and insert the data.
Algorithm
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
while(1) {
parent = current;
if(current == NULL) {
parent->leftChild = tempNode;
return;
}
} //go to right of the tree
else {
current = current->rightChild;
https://www.tutorialspoint.com/data_structures_algorithms/binary_search_tree.htm 3/3