Data Structures · Visualization
BST: Introduction
Binary Search Tree
A binary search tree (BST) is a binary tree that follows one important ordering rule at every node: everything in its left subtree is smaller than the node's value, and everything in its right subtree is larger. Time: O(h) for search/insert/delete, where h is the tree's height (O(log n) balanced, O(n) worst case if skewed). Space: O(n).
Big-O: Search/insert/delete O(log n) on a balanced tree, O(n) worst case.
BST: Introduction
Binary Search TreeA binary search tree (BST) is a binary tree that follows one important ordering rule at every node: everything in its left subtree is smaller than the node's value, and everything in its right subtree is larger. This rule, applied consistently, means you can search, insert, or delete by always knowing which direction to go, similar to how binary search works on a sorted array.
How BST: Introduction Works
- Pick a root value.
- Any value less than a node goes into that node's left subtree.
- Any value greater than a node goes into that node's right subtree.
- Apply this rule recursively at every node as the tree grows.
BST: Introduction Worked Example
Input: Insert 8, 3, 10, 1, 6 into an empty BST
- 8 becomes the root
- 3 < 8 → goes left of 8
- 10 > 8 → goes right of 8
- 1 < 8, 1 < 3 → goes left of 3
- 6 < 8, 6 > 3 → goes right of 3
Output: 8 / \ 3 10 / \ 1 6
Press ▶ Run to watch it step by step.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Invariant at every node:
# left.val < node.val < right.val
# example: introBST: Introduction Time & Space Complexity
When to Use BST: Introduction
- Maintaining a dynamic, sorted collection that supports fast search, insert, and delete
- Implementing ordered maps and sets
- Range queries (finding all values between X and Y)
- The foundation for self-balancing trees like AVL and Red-Black trees
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.