Part 17 / Topic 11 of 20
Trees
A tree is nodes connected so that each one (except the root) has exactly one parent, with no cycles - a shape, not a sequence. A binary search tree (BST) keeps every left child smaller and every right child bigger than its parent, so searching, inserting and deleting are all O(log n) on average, when the tree is reasonably balanced. That ordering rule applies to every descendant, not just the direct children - a node deep in the left subtree must still be smaller than every one of its ancestors, which is why validating a BST needs a running low/high bound passed down the recursion, not just a check against each node's immediate parent. In the worst case (for example, inserting already-sorted data one by one, which builds a straight line instead of a spread-out tree) it degrades to O(n) - no better than a list. Think of a company org chart: the CEO at the root, each manager's reports branching below them, and "how many levels deep is this employee?" is a tree question.
| Operation (BST) | Balanced (average) | Unbalanced (worst case) |
|---|---|---|
| search / insert / delete | O(log n) | O(n) |
| visit every node (any traversal) | O(n) | O(n) |
class TreeNode:
def __init__(self, value):
self.value = value
self.left = self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = TreeNode(value)
return
node = self.root
while True:
if value < node.value:
if node.left is None:
node.left = TreeNode(value); return
node = node.left
else:
if node.right is None:
node.right = TreeNode(value); return
node = node.right
bst = BinarySearchTree()
for employee_id in [50, 30, 70, 20, 40, 60, 80]:
bst.insert(employee_id)
In-order traversal (left, node, right) always visits a BST's values in sorted order:
def in_order(node, result):
if node is None:
return
in_order(node.left, result)
result.append(node.value)
in_order(node.right, result)
return result
print(in_order(bst.root, [])) # [20, 30, 40, 50, 60, 70, 80]
Level-order (breadth-first) traversal visits one level at a time, using a deque as a FIFO queue - the same queue pattern from the stacks-and-queues topic:
from collections import deque
def level_order(root):
if root is None:
return []
levels, queue = [], deque([root])
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.value)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
levels.append(level)
return levels
print(level_order(bst.root)) # [[50], [30, 70], [20, 40, 60, 80]]
Real-world example: a project folder's total size is a recursive tree walk: a folder's size is its own files' size plus every subfolder's size, added up from the deepest files upward - the same "combine the children's answers" shape as in_order above, just summing instead of collecting.
⚠️ Inserting already-sorted data one at a time builds a tree that is really a straight line (every new node becomes a right child), losing the O(log n) benefit entirely. Real-world code reaches for a library's self-balancing tree, or just sorts the data instead, rather than hand-rolling a balancing BST.
Practice: tree traversal (in-order, pre-order, level-order) and reconstructing structure from it; validate or search a BST; compute tree height, or the lowest common ancestor of two nodes.
Practice on LeetCode - start here: Maximum Depth of Binary Tree · Invert Binary Tree · Same Tree · Binary Tree Level Order Traversal · Lowest Common Ancestor of a Binary Search Tree · Validate Binary Search Tree
Show the full practice list (27 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Symmetric Tree | Easy |
| Balanced Binary Tree | Easy |
| Minimum Depth of Binary Tree | Easy |
| Merge Two Binary Trees | Easy |
| Path Sum | Easy |
| Subtree of Another Tree | Easy |
| Binary Tree Inorder Traversal | Easy |
| Binary Tree Preorder Traversal | Easy |
| Binary Tree Postorder Traversal | Easy |
| Average of Levels in Binary Tree | Easy |
| Search in a Binary Search Tree | Easy |
| Convert Sorted Array to Binary Search Tree | Easy |
| Range Sum of BST | Easy |
| Two Sum IV - Input is a BST | Easy |
| Diameter of Binary Tree | Easy |
| Insert into a Binary Search Tree | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Binary Tree Right Side View | Medium |
| Binary Tree Zigzag Level Order Traversal | Medium |
| Count Good Nodes in Binary Tree | Medium |
| Path Sum II | Medium |
| Kth Smallest Element in a BST | Medium |
| Delete Node in a BST | Medium |
| Lowest Common Ancestor of a Binary Tree | Medium |
| Construct Binary Tree from Preorder and Inorder Traversal | Medium |
| Binary Search Tree Iterator | Medium |
| Binary Tree Maximum Path Sum | Hard |
| Serialize and Deserialize Binary Tree | Hard |
Full program: examples/11_trees.py.
Exercise 11: Trees — validate a binary search tree
Scenario: A colleague built a tree by hand and you need to confirm it is really a valid BST (every left value is smaller, every right value is bigger, all the way down) before trusting in_order() to return sorted data.
What to do: Using the TreeNode class from examples/11_trees.py, write is_valid_bst(node, low=float("-inf"), high=float("inf")) -> bool that recursively checks every node's value is within the (low, high) range handed down from its ancestors. Build the valid and broken trees below by hand (set .left/.right directly) and print both checks.
Starting data (build by hand, do not use .insert()):
Valid tree: Broken tree (right subtree has a 25, which is < 30):
30 30
/ \ / \
20 40 20 40
/
25
Sample output:
Valid tree is a valid BST: True
Broken tree is a valid BST: False
Show the solution to Exercise 11
"""Exercise 11: Trees - validate a binary search tree.
Run: python ex09.py (macOS/Linux: python3 ex09.py)
"""
class TreeNode:
def __init__(self, value):
self.value = value
self.left: "TreeNode | None" = None
self.right: "TreeNode | None" = None
def is_valid_bst(node: TreeNode | None, low=float("-inf"), high=float("inf")) -> bool:
if node is None:
return True
if not (low < node.value < high):
return False
return is_valid_bst(node.left, low, node.value) and is_valid_bst(node.right, node.value, high)
def build_valid_tree() -> TreeNode:
root = TreeNode(30)
root.left = TreeNode(20)
root.right = TreeNode(40)
return root
def build_broken_tree() -> TreeNode:
root = TreeNode(30)
root.left = TreeNode(20)
root.right = TreeNode(40)
root.right.left = TreeNode(25) # 25 < 30, but it's in the RIGHT subtree: invalid
return root
def main() -> None:
print("Valid tree is a valid BST:", is_valid_bst(build_valid_tree()))
print("Broken tree is a valid BST:", is_valid_bst(build_broken_tree()))
if __name__ == "__main__":
main()