What is a Binary Search Tree
A Binary Search Tree (BST) is a binary tree where each node has a key and meet the following requirements:
- The
left subtreeof a node contains nodes with keyssmallerthan the node's key - The
right subtreeof a node contains nodes with keyslargerthan the node's key - The
leftandrightsubtree arebinary search trees

Here is how a node could look like. For simplicity, the key has type Key and the value has type Value.
public class Node
{
public Key Key;
// associated value
public Value Value;
public Node Left;
public Node Right;
public Node(Key key, Value value)
{
Key = key;
Value = value;
}
}
Examples
Best case

Typical case

Worst case

Tree operations
Search operation
It searches for a node using it’s key, and returns it’s value.
the search operation starts from the root node
- if it’s
lessthan, then goleft - if it’s
greaterthan, goright - if it’s
equal, we aredone, return a value - If the tree is empty, or we reached
nulllink, returnnull. We have a search miss.
public Value Search(string key)
{
Node node = root;
while (node != null)
{
int compareResult = key.CompareTo(node.Key);
if (compareResult < 0)
{
node = node.Left;
}
else if (compareResult > 0)
{
node = node.Right;
}
else
{
return node.Value;
}
}
return null;
}
Time complexity: In average cases the time complexity is O(logn), in the worst case O(n)
Put operation
Insert a node of a key and a value in the BST. The method searches the tree recursively until it finds a null link, and all that we need to do is replace that link with a new node. If the key already exists, it updates the value.
public void Put(Key key, Value value)
{
root = Put(root, key, value);
}
private Node Put(Node node, Key key, Value value)
{
if (node == null)
{
return new Node(key, value);
}
int compareResult = key.CompareTo(node.Key);
if (compareResult < 0)
{
node.Left = Put(node.Left, key, value);
}
else if(compareResult > 0)
{
node.Right = Put(node.Right, key, value);
}
else if (compareResult == 0)
{
node.Value = value;
}
return node;
}
Time complexity: In average cases the time complexity is O(logn), in the worst case O(n)
Recent articles
Nice to read