Module 8 · Trees and Heaps · Lesson 27 of 40
Binary search trees
A tree where smaller values go left and bigger go right, so search, insert and delete follow one path.
In this lesson · about 22 minutes
- State the BST rule
- Search and insert in a BST
- Explain why balance matters: O(log n) vs O(n)
A binary search tree (BST) is a binary tree with one rule at every node:
Everything in the left subtree is smaller. Everything in the right subtree is bigger.
This makes it work like binary search, but in a tree you can also add and remove items easily.
Search
Start at the root. If the target is smaller, go left; if bigger, go right; if equal, found. If you fall off the tree (reach None), it isn't there.
Insert
Search for the value. When you fall off the tree, that empty spot is exactly where the new value belongs.
Delete (three cases)
- A leaf: just remove it.
- One child: let the child take its place.
- Two children: replace its value with the smallest value in its right subtree (the "inorder successor"), then delete that node instead.
Min, max and sorted order
The smallest value is found by going left until you can't. The biggest: go right. An inorder traversal visits a BST in sorted order.
Balance matters
Each operation follows one path from the root, so it costs O(h), where h is the height. In a balanced tree, h ≈ log n, so everything is O(log n). But insert 1, 2, 3, 4, 5 in that order and you get a skewed tree, a straight line with h = n, and everything becomes O(n). Self-balancing trees (like AVL and red-black trees) fix this automatically.
Try it · see it work
Insert into a BST
Insert 65, then 35, then 85. Read the path each value takes. Then try inorder.
Step 1 of 9Inorder = left subtree, then node, then right subtree.
Exercise
Search a BST
Write bst_contains(node, target) that returns True if the target is in the BST. Follow one path: go left when the target is smaller, right when bigger. (Use a loop or recursion.)
Code that runs before yours
from collections import deque
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree(values):
"""Build a tree from a level-order list such as [1, 2, 3, None, 4]."""
if not values or values[0] is None:
return None
root = TreeNode(values[0])
queue = deque([root])
i = 1
while queue and i < len(values):
node = queue.popleft()
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1
return root
def bst_from(values):
root = None
def put(node, v):
if node is None:
return TreeNode(v)
if v < node.value:
node.left = put(node.left, v)
elif v > node.value:
node.right = put(node.right, v)
return node
for v in values:
root = put(root, v)
return root
def inorder(node):
return inorder(node.left) + [node.value] + inorder(node.right) if node else []
Exercise
Insert into a BST
Write a recursive insert(node, value) that adds the value to the BST and returns the (possibly new) root. If the value is already there, change nothing.
Code that runs before yours
from collections import deque
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree(values):
"""Build a tree from a level-order list such as [1, 2, 3, None, 4]."""
if not values or values[0] is None:
return None
root = TreeNode(values[0])
queue = deque([root])
i = 1
while queue and i < len(values):
node = queue.popleft()
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1
return root
def bst_from(values):
root = None
def put(node, v):
if node is None:
return TreeNode(v)
if v < node.value:
node.left = put(node.left, v)
elif v > node.value:
node.right = put(node.right, v)
return node
for v in values:
root = put(root, v)
return root
def inorder(node):
return inorder(node.left) + [node.value] + inorder(node.right) if node else []
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.