Python · Module 12 · Lesson 41 min read

Recursion & Trees

Recursion

A function that calls itself on a smaller version of the problem. Every recursive function needs:

  1. A base case that stops the recursion.
  2. A recursive case that moves toward the base case.

Python's default recursion limit is about 1000 calls. Going deeper raises RecursionError, so use a loop for very deep problems.

Trees

A tree is made of nodes, each with children. A binary search tree (BST) keeps smaller values on the left and larger on the right, so search, insert and delete take O(log n) when the tree is balanced.

Traversals

OrderVisitUse
In-orderleft → node → rightsorted output from a BST
Pre-ordernode → left → rightcopying a tree
Post-orderleft → right → nodedeleting a tree
Level-orderrow by row (with a queue)shortest paths, printing levels

💡 Trees are everywhere: folders on your computer, HTML pages, JSON data and database indexes.

▶️ Runs in the app.

Example

Python
from collections import deque

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def insert(root, value):
    if root is None:                      # base case
        return Node(value)
    if value < root.value:
        root.left = insert(root.left, value)
    else:
        root.right = insert(root.right, value)
    return root

def in_order(root):
    if root is None:
        return []
    return in_order(root.left) + [root.value] + in_order(root.right)

def height(root):
    return 0 if root is None else 1 + max(height(root.left), height(root.right))

def level_order(root):
    rows, queue = [], deque([root])
    while queue:
        rows.append([n.value for n in queue])
        queue = deque(c for n in queue for c in (n.left, n.right) if c)
    return rows

root = None
for v in [50, 30, 70, 20, 40, 60, 80]:
    root = insert(root, v)

print(in_order(root))      # [20, 30, 40, 50, 60, 70, 80]
print(height(root))        # 3
print(level_order(root))   # [[50], [30, 70], [20, 40, 60, 80]]