A tree is a structure that branches out, like a family tree or a folder structure. It starts at the root and each node can have children. Nodes with no children are leaves.
A BST follows one golden rule at every node: smaller values go left, larger values go right. This keeps the data organized so you can search it in O(log n) — just like binary search!
def insert(root, value):
if root is None:
return Node(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
🚶 Traversals — visiting every node
Because trees branch, we use recursion to visit nodes. In-order traversal of a BST magically returns the values in sorted order!
def in_order(root):
if root is None:
return
in_order(root.left) # 1. left subtree
print(root.value) # 2. this node
in_order(root.right) # 3. right subtree
💡 Three traversal orders
In-order (left, node, right) → sorted output for a BST.
Pre-order (node, left, right) → copy/serialize a tree.
Post-order (left, right, node) → delete a tree safely.
✅ What you learned
A tree branches from a root; nodes have children, leaves have none.
A binary tree node has left and right children.
A BST keeps smaller left, larger right → fast O(log n) search.
In-order traversal of a BST prints values in sorted order.
🎮 Time to Practice!
Grow a tree, then climb it with recursion. 🌳
🌱
Task 1: Build a Tiny Tree
Easy
Give the root (8) a left child of 3 and a right child of 10. Then print the root, left, and right values → 8, 3, 10.
Complete the in-order traversal (left, then node, then right). The BST is built for you. Running it should print the values in sorted order: 1, 3, 6, 8, 10, 14.
def in_order(root):
if root is None:
return
in_order(root.left)
print(root.value)
in_order(root.right)
in_order(root)
📐
Task 3: Tree Height
Tricky
The height of a tree is the longest path from root to a leaf. Recursively: height = 1 + the taller of the two children. An empty tree has height 0. This tree's height is 3.
def height(root):
if root is None:
return 0
return 1 + max(height(root.left), height(root.right))
print(height(root))