Menu
Coddy logo textTech

Binary Search Tree (BST)

Last updated

A binary search tree keeps its values in sorted order: for every node, all values in its left subtree are smaller and all values in its right subtree are larger. To insert or find a value you start at the root and repeatedly go left or right depending on the comparison, so each step halves the search space. Press play above to watch values placed by comparison and a search walk down the tree.

On a balanced tree these operations run in O(log n) time. The catch: inserting already-sorted data makes the tree degenerate into a linked list with O(n) operations - which is exactly why self-balancing variants like AVL and red-black trees exist.

Time & space complexity

OperationBalancedWorst case (skewed)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
SpaceO(n)O(n)

Step by step (insert)

StepWhat happens
1If the tree is empty, the new value becomes the root.
2Otherwise start at the root.
3If the value is smaller, go to the left child; if larger, go right.
4Repeat until you reach an empty spot.
5Attach the new value as a leaf there.

Worked example

Inserting [5, 3, 8, 1, 4] into an empty tree, one value at a time:

InsertPath takenAction
5-Tree is empty, so 5 becomes the root.
353 < 5, go left; the spot is empty, attach 3 as the left child of 5.
858 > 5, go right; the spot is empty, attach 8 as the right child of 5.
15 -> 31 < 5 go left, then 1 < 3 go left; attach 1 as the left child of 3.
45 -> 34 < 5 go left, then 4 > 3 go right; attach 4 as the right child of 3.

When to use a binary search tree

Use it whenAvoid it when
You need sorted order plus fast lookups, and insertions arrive in random order.Your data arrives already sorted - an unbalanced BST degrades to O(n) per operation.
You want in-order traversal to yield values in sorted sequence for free.You only need membership tests and no ordering - a hash table gives O(1) average lookups.
You need range queries or the successor/predecessor of a key.You need guaranteed O(log n) bounds - reach for a self-balancing AVL or red-black tree instead.
The dataset changes often and a static sorted array would be costly to update.The dataset is fixed and read-only - a sorted array with binary search is simpler and cache-friendly.

Binary Search Tree code

A clean, runnable Binary Search Tree implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Binary Search Tree code in Python

Python
1class Node:2    def __init__(self, key):3        self.key = key4        self.left = None5        self.right = None6
7
8def insert(node, key):9    if node is None:10        return Node(key)11    if key < node.key:12        node.left = insert(node.left, key)13    elif key > node.key:14        node.right = insert(node.right, key)15    return node  # duplicates are ignored16
17
18def search(node, key):19    if node is None:20        return False21    if key == node.key:22        return True23    if key < node.key:24        return search(node.left, key)25    return search(node.right, key)26
27
28def inorder(node):29    if node is None:30        return []31    return inorder(node.left) + [node.key] + inorder(node.right)32
33
34root = None35for key in [8, 3, 10, 1, 6, 14, 4, 7]:36    root = insert(root, key)37
38print("Inorder (sorted):", inorder(root))39print("search(6): ", search(root, 6))40print("search(5): ", search(root, 5))
Run this code in the Python Playground

Binary Search Tree FAQ

What is the time complexity of a binary search tree?
Search, insert, and delete are O(log n) on a balanced tree, because each comparison discards half the remaining nodes. In the worst case - a tree skewed into a chain by sorted insertions - they degrade to O(n).
What is the difference between a binary tree and a binary search tree?
A binary tree is any tree where each node has at most two children, with no ordering rule. A binary search tree adds the invariant that left-subtree values are smaller and right-subtree values are larger than the node, which is what enables fast searching.
Why can a binary search tree become slow?
If values are inserted in sorted (or reverse-sorted) order, every new node goes to the same side, producing a tall, skewed tree that behaves like a linked list - O(n) per operation. Self-balancing trees (AVL, red-black) rotate nodes to prevent this.
What is the difference between a binary search tree and a hash table?
A hash table gives O(1) average lookups but stores keys in no particular order, so it cannot answer range or successor queries. A binary search tree is slightly slower at O(log n) but keeps keys ordered, letting you traverse them in sorted order and find nearest values. Choose a BST when order matters and a hash table when you only need membership tests.
When should I use a self-balancing tree instead of a plain BST?
Use a self-balancing tree (AVL, red-black) whenever you cannot control the insertion order and need guaranteed O(log n) performance. A plain BST is fine for teaching, for small datasets, or when keys arrive in random order, but it offers no protection against the skewed worst case.
Does an in-order traversal of a BST return sorted values?
Yes. Visiting the left subtree, then the node, then the right subtree yields the keys in ascending order, which follows directly from the BST invariant. A common mistake is expecting the same from a plain binary tree - without the ordering rule, in-order traversal produces no meaningful sequence.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED