Binary Search Tree in Python
A binary search tree keeps smaller values in the left subtree and larger values in the right subtree, so every comparison rules out half of the remaining tree.
What is Binary Search Tree?
A binary search tree keeps smaller values in the left subtree and larger values in the right subtree, so every comparison rules out half of the remaining tree.
Build a binary search tree in Python: insert values, search them and list them in sorted order.
When should you use it?
- Practice problem solving and data structures.
- Process data when every algorithm step must be explicit.
- Prepare for programming exercises, exams, and interviews.
See how it works
Insert values to see where they land, search for a value to follow its path, and run a traversal to see the visit order.
Example code
class Node:
def __init__(self, value):
self.value = value
self.left = None # smaller values go left
self.right = None # larger values go right
def insert(node, value):
if node is None:
return Node(value)
if value < node.value:
node.left = insert(node.left, value)
elif value > node.value:
node.right = insert(node.right, value)
return node
def contains(node, value):
# Each comparison discards one whole subtree.
while node is not None:
if value == node.value:
return True
node = node.left if value < node.value else node.right
return False
def inorder(node):
# Left subtree, node, right subtree: visits values in sorted order.
if node is None:
return []
return inorder(node.left) + [node.value] + inorder(node.right)
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
root = None
for value in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, value)
print("inorder:", inorder(root))
print("contains 60:", contains(root, 60))
print("contains 65:", contains(root, 65))
print("height:", height(root))
Expected output
inorder: [20, 30, 40, 50, 60, 70, 80]
contains 60: True
contains 65: False
height: 3
How it works
insert() walks down from the root and attaches the value where it belongs. contains() follows a single path, which takes O(log n) steps in a balanced tree. An inorder traversal visits left, node, right, so the values come out sorted.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Try empty, single-item, and duplicate-value inputs.
- Print state after every step to observe the algorithm.
- Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Tree Diameter A tree is a connected undirected graph with no cycles. Medium
- Composite Folder Sizes Compute the total size of every folder in a tree where folders contain files and other folders. Medium