Trees & BST, Part 1: Binary Trees & Traversals
After this lesson, you will be able to:
- Name and compute every tree term: root, leaf, height, depth, subtree, degree
- Implement a TreeNode and a BST with insert, search, and min/max
- Apply all four traversals (inorder, preorder, postorder, BFS) both recursively and iteratively
- Choose the right traversal for the task: sorted output, reconstruction, deletion order, shortest path
Before you start
#Tree Terminology: The Vocabulary You Must Own
#Core Vocabulary
Tree Terminology Example
The same tree as plain text, with the depth of each row on the left:
depth 0: A <- root
/ \
depth 1: B C <- B and C are siblings
/ \ \
depth 2: D E F <- D, E and F are leaves
Read it from the top down, one word at a time.
| Term | Meaning | In the tree above |
|---|---|---|
| Root | The top node, with no parent | A |
| Leaf | A node with no children | D, E, F |
| Internal node | A node with at least one child | A, B, C |
| Parent | The node directly above | A is the parent of B and C |
| Children | The nodes directly below | B and C are the children of A |
| Sibling | Nodes that share the same parent | B and C are siblings |
| Subtree | A node plus everything below it | B's subtree is |
| Edge | The link between a parent and a child | A-B, A-C, B-D, B-E, C-F |
| Degree | The number of children a node has | A has degree 2; D has degree 0 |
| Height of a node | Edges on the longest path down to a leaf | Height of B = 1; height of A = 2 |
| Height of the tree | The height of the root | 2 |
| Depth of a node | Edges on the path from the root to it | Depth of A = 0; depth of D = 2 |
| Level | All the nodes at the same depth | Level 0: ; level 1: ; level 2: |
height asks the two subtrees how tall they are and adds one. depth walks down from the root and counts the steps. Both use recursion: a function that calls itself on a smaller piece, here on the left and right subtree.def height(root) -> int:
"""Recursive height computation. O(n): it must visit every node."""
if root is None:
return -1 # an empty tree is -1, so a single node gets height 0
return 1 + max(height(root.left), height(root.right))
def depth(root, target, current_depth: int = 0) -> int:
"""Find depth of the node containing target value."""
if root is None:
return -1
if root.val == target:
return current_depth
left = depth(root.left, target, current_depth + 1)
if left != -1:
return left
return depth(root.right, target, current_depth + 1)In a perfectly balanced binary tree with 15 nodes (4 levels: 1 + 2 + 4 + 8 nodes), what is the height?
Keep this definition of height in mind: the rest of this lesson measures every tree with it.
#Binary Tree Implementation
None.from __future__ import annotations
from typing import Any, Optional, List
from collections import deque
class TreeNode:
"""A node in a binary tree."""
def __init__(self, val: Any) -> None:
self.val = val
self.left: Optional[TreeNode] = None
self.right: Optional[TreeNode] = None
def __repr__(self) -> str:
return f"TreeNode({self.val!r})"
def is_leaf(self) -> bool:
"""A leaf node has no children."""
return self.left is None and self.right is None
class BinaryTree:
"""
General binary tree with breadth-first insertion.
(The BST, covered later in this lesson, uses a different ordered insert.)
"""
def __init__(self) -> None:
self.root: Optional[TreeNode] = None
def insert(self, val: Any) -> None:
"""
Insert a value using BFS (level-order) insertion.
Fills left child first, then right, level by level.
O(n) in the worst case.
"""
new_node = TreeNode(val)
if self.root is None:
self.root = new_node
return
# BFS to find the first node with a free child slot
queue = deque([self.root])
while queue:
node = queue.popleft()
if node.left is None:
node.left = new_node
return
else:
queue.append(node.left)
if node.right is None:
node.right = new_node
return
else:
queue.append(node.right)
def height(self) -> int:
"""Height of the tree. O(n) — visits every node."""
def _height(node: Optional[TreeNode]) -> int:
if node is None:
return -1
return 1 + max(_height(node.left), _height(node.right))
return _height(self.root)
def count_nodes(self) -> int:
"""Count all nodes recursively. O(n)."""
def _count(node: Optional[TreeNode]) -> int:
if node is None:
return 0
return 1 + _count(node.left) + _count(node.right)
return _count(self.root)
def count_leaves(self) -> int:
"""Count leaf nodes. O(n)."""
def _leaves(node: Optional[TreeNode]) -> int:
if node is None:
return 0
if node.is_leaf():
return 1
return _leaves(node.left) + _leaves(node.right)
return _leaves(self.root)#Tree Traversals: Four Ways to Visit Every Node
#DFS: Three Orders (Recursive)
Start with the smallest tree that shows the difference: a root 2 with a left child 1 and a right child 3. Every traversal visits the same three nodes, only in a different order.
- Inorder: left subtree, then the node, then the right subtree. Result: 1, 2, 3.
- Preorder: the node first, then left, then right. Result: 2, 1, 3.
- Postorder: left, then right, then the node last. Result: 1, 3, 2.
The bigger tree above follows the same rule at every node. In the code, "recursive" means each function calls itself on the left subtree and on the right subtree.
def inorder(root: Optional[TreeNode]) -> List[Any]:
"""
Left -> Root -> Right.
Produces SORTED output for a BST, which is very useful.
Think: 'visit the left subtree completely, then self, then right.'
"""
if root is None:
return []
return inorder(root.left) + [root.val] + inorder(root.right)
# For the example tree: [1, 2, 3, 4, 5, 6, 7]
def preorder(root: Optional[TreeNode]) -> List[Any]:
"""
Root -> Left -> Right.
Root is processed BEFORE its subtrees.
Use case: copy or save a tree (preorder is an insertion order
that rebuilds the same BST shape from scratch).
"""
if root is None:
return []
return [root.val] + preorder(root.left) + preorder(root.right)
# For the example tree: [4, 2, 1, 3, 6, 5, 7]
def postorder(root: Optional[TreeNode]) -> List[Any]:
"""
Left -> Right -> Root.
Root is processed AFTER both subtrees.
Use case: (1) delete a tree (free children before parent),
(2) evaluate expression trees (compute sub-expressions first).
"""
if root is None:
return []
return postorder(root.left) + postorder(root.right) + [root.val]
# For the example tree: [1, 3, 2, 5, 7, 6, 4]#BFS: Level-Order Traversal
def level_order(root: Optional[TreeNode]) -> List[List[Any]]:
"""
Visit nodes level by level, left to right.
Returns a list of levels — each level is a list of values.
Use case: shortest path in unweighted trees, printing tree structure,
finding minimum depth.
Uses a queue (deque). Do not use recursion for BFS.
"""
if root is None:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue) # snapshot: how many nodes at this level
level_values = []
for _ in range(level_size):
node = queue.popleft()
level_values.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level_values)
return result
# For the example tree: [[4], [2, 6], [1, 3, 5, 7]]#Iterative DFS: Using an Explicit Stack
from collections import deque
def inorder_iterative(root: Optional[TreeNode]) -> List[Any]:
"""
Iterative inorder (Left -> Root -> Right).
Uses an explicit stack. Safe for very deep trees (no recursion limit).
"""
result = []
stack = []
current = root
while current is not None or stack:
# Go as far left as possible, pushing nodes onto the stack
while current is not None:
stack.append(current)
current = current.left
# Process the node (it has no more left children to push)
current = stack.pop()
result.append(current.val)
# Move to the right subtree
current = current.right
return result
def preorder_iterative(root: Optional[TreeNode]) -> List[Any]:
"""
Iterative preorder (Root -> Left -> Right).
Push the right child first so the left one is processed first (a stack is LIFO).
"""
if root is None:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
result.append(node.val) # process root
if node.right:
stack.append(node.right) # right pushed first (processed second)
if node.left:
stack.append(node.left) # left pushed second (processed first)
return result
def postorder_iterative(root: Optional[TreeNode]) -> List[Any]:
"""
Iterative postorder (Left -> Right -> Root).
Trick: do a modified preorder (Root -> Right -> Left), then reverse the result.
"""
if root is None:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
result.append(node.val)
if node.left:
stack.append(node.left) # left pushed first (reversed later)
if node.right:
stack.append(node.right) # right pushed second
return result[::-1] # reverse gives Left -> Right -> Root#Comparing Traversal Outputs
Traversal Outputs
| Traversal | Output | Key Property |
|---|---|---|
| Inorder | [1, 2, 3, 4, 5, 6, 7] | SORTED (BST property) |
| Preorder | [4, 2, 1, 3, 6, 5, 7] | Root first (insertion order) |
| Postorder | [1, 3, 2, 5, 7, 6, 4] | Root last (children first) |
| BFS | [[4], [2,6], [1,3,5,7]] | Level by level |
Choosing the right traversal
| Task | Best Traversal |
|---|---|
| Get sorted values from BST | Inorder |
| Copy/reconstruct the tree | Preorder |
| Delete all nodes (free memory) | Postorder |
| Find the fewest edges between nodes | BFS (level-order) |
| Evaluate an expression tree | Postorder |
| Find all leaf nodes | Any DFS |
| Save and rebuild a tree | BFS or preorder |
On that tree, inorder gives [1,2,3,4,5,6,7], preorder gives [4,2,1,3,6,5,7], and postorder gives [1,3,2,5,7,6,4]. Which one would you save to rebuild the identical tree later?
In-order traversal of a small BST — left, visit, right
Step through the recursive calls and returns to watch the call tree grow, results fill in, and the call stack change.
A recursion call tree for the supplied function, shown above its source code with a call stack panel beside it. It starts at step 0 with an empty tree and empty stack; each step adds a call or fills in a return value, until the tree is complete.
def inorder(node):
if node is None:
return
inorder(node.left)
visit(node.val)
inorder(node.right)#Binary Search Tree: Full Implementation
n, all values in the left subtree of n are less than n.val, and all values in its right subtree are greater. This one rule is what makes search fast: at each node you can ignore one whole side. The work is at most the height of the tree, which we write O(h), where h is the height.BST property check at node 5: All values in left subtree (3, 1, 4) < 5. All values in right subtree (7, 6, 8) > 5.
from __future__ import annotations
from typing import Any, List, Optional, Tuple
class BSTNode:
"""Node for a Binary Search Tree."""
def __init__(self, val: Any) -> None:
self.val = val
self.left: Optional[BSTNode] = None
self.right: Optional[BSTNode] = None
class BST:
"""
Binary Search Tree.
Average-case O(log n) insert/search/delete for balanced trees.
Worst-case O(n) when the tree collapses into a line (see below).
Inorder traversal always returns a sorted sequence.
"""
def __init__(self) -> None:
self.root: Optional[BSTNode] = None
self._size: int = 0
# ------------------------------------------------------------------
# Insert
# ------------------------------------------------------------------
def insert(self, val: Any) -> None:
"""
Insert a value into the BST.
Navigates left if val < current, right if val > current.
Ignores duplicate values (set semantics).
O(h) where h is the tree height.
"""
self.root = self._insert_recursive(self.root, val)
def _insert_recursive(self, node: Optional[BSTNode], val: Any) -> BSTNode:
"""
Returns the (possibly new) root of the subtree.
THE KEY PATTERN: node.left = _insert(node.left, val)
Always reassign, because when node is None we return a new BSTNode.
"""
if node is None:
self._size += 1
return BSTNode(val) # base case: found the insertion spot
if val < node.val:
node.left = self._insert_recursive(node.left, val)
elif val > node.val:
node.right = self._insert_recursive(node.right, val)
# val == node.val: duplicate, do nothing (this BST stores each value once)
return node
def insert_iterative(self, val: Any) -> None:
"""Iterative insert — avoids recursion overhead for very deep trees."""
new_node = BSTNode(val)
if self.root is None:
self.root = new_node
self._size += 1
return
current = self.root
while True:
if val < current.val:
if current.left is None:
current.left = new_node
self._size += 1
return
current = current.left
elif val > current.val:
if current.right is None:
current.right = new_node
self._size += 1
return
current = current.right
else:
return # duplicate
Type a value and watch it walk down the tree, going left when it is smaller and right when it is larger. Search takes the same walk. Delete is explained in Part 2. Try inserting 1, 2, 3, 4, 5 in order and watch the tree lean into a line.
# ------------------------------------------------------------------
# Search
# ------------------------------------------------------------------
def search(self, val: Any) -> bool:
"""Return True if val is in the BST. O(h)."""
return self._search_recursive(self.root, val)
def _search_recursive(self, node: Optional[BSTNode], val: Any) -> bool:
if node is None:
return False
if val == node.val:
return True
if val < node.val:
return self._search_recursive(node.left, val)
return self._search_recursive(node.right, val)
def search_iterative(self, val: Any) -> bool:
"""Iterative search — O(h), O(1) space."""
current = self.root
while current is not None:
if val == current.val:
return True
current = current.left if val < current.val else current.right
return False
Which property must every node in a Binary Search Tree satisfy?
# ------------------------------------------------------------------
# Min and Max
# ------------------------------------------------------------------
def min_value(self) -> Any:
"""
Minimum value is always at the leftmost node.
Keep going left until left is None.
O(h).
"""
if self.root is None:
raise ValueError("BST is empty")
node = self.root
while node.left is not None:
node = node.left
return node.val
def max_value(self) -> Any:
"""Maximum is at the rightmost node. O(h)."""
if self.root is None:
raise ValueError("BST is empty")
node = self.root
while node.right is not None:
node = node.right
return node.val
def _min_node(self, node: BSTNode) -> BSTNode:
"""Helper: return the node with minimum value in a subtree."""
while node.left is not None:
node = node.left
return node
# ------------------------------------------------------------------
# Traversals
# ------------------------------------------------------------------
def inorder(self) -> List[Any]:
"""Returns a SORTED list of all values. O(n)."""
result: List[Any] = []
def _inorder(node: Optional[BSTNode]) -> None:
if node is None:
return
_inorder(node.left)
result.append(node.val)
_inorder(node.right)
_inorder(self.root)
return result
# ------------------------------------------------------------------
# Utilities
# ------------------------------------------------------------------
def __len__(self) -> int:
return self._size
def __contains__(self, val: Any) -> bool:
return self.search(val)
def __repr__(self) -> str:
return f"BST(inorder={self.inorder()})"Insert 1, 2, 3, 4, 5 into an empty BST in that order. What shape results, and what does search cost?
#BST Time Complexity
| Operation | Average (balanced) | Worst case (collapsed into a line) |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Min / Max | O(log n) | O(n) |
| Inorder (all) | O(n) | O(n) |
#When the Tree Collapses Into a Line: Why the Worst Case Is O(n)
1, 2, 3, 4, 5:This is just a linked list. The height is n - 1 = 4. Searching for 5 visits 5 nodes: O(n), not O(log n).
[3, 1, 4, 2, 5] — same values, different order:The height is 2. Searching for 5 takes 3 comparisons: O(log n).
sortedcontainers is a third-party package that is not available in the browser's Python. This cell is read-only; to run it on your own machine, first install it with pip install sortedcontainers.# In everyday Python, use sortedcontainers for a sorted structure that stays fast:
from sortedcontainers import SortedList
sl = SortedList([3, 1, 4, 1, 5, 9, 2, 6])
sl.add(7) # O(log n) insert maintaining sorted order
print(sl) # SortedList([1, 1, 2, 3, 4, 5, 6, 7, 9])
print(sl.bisect_left(5)) # O(log n) binary search, gives index 5
sl.discard(4) # O(log n) delete
print(sl[2]) # O(log n) index access#Interactive Visualization: Tree Operations & Traversals
Build BSTs by hand, watch all four traversal orders animate, and explore Trie prefix matching:
#Code Playground
Tests: assert bst.inorder() == [1, 3, 4, 5, 6, 7, 8]; assert bst.search(4) == True; assert bst.search(9) == False
#Key Takeaways
- The BST rule is the whole data structure: every left descendant < node < every right descendant. Break it once and the O(log n) speed is gone
- Four traversals give four different results: inorder gives sorted output, preorder lets you rebuild the tree, postorder handles children before the parent, level-order finds the fewest edges
- The recursive insert pattern:
node.left = self._insert(node.left, val)— always reassign because the base case returns a fresh node, and alwaysreturn nodeat the end of the helper - Unbalanced BSTs slow down to O(n): inserting sorted data creates a linked list, so use
sortedcontainers.SortedListwhen you need dependable O(log n) lookups in everyday Python code - Recursive DFS plus an iterative BFS loop cover most tree problems: internalize the recursive DFS template (base case, left recursion, right recursion, return value) and the BFS deque loop until they are automatic
#Quiz
You perform an inorder traversal of a BST and get [1, 2, 3, 5, 7, 8]. Which value was most recently deleted from the original BST if it contained [1, 2, 3, 4, 5, 7, 8]?