Topic 06 of 14

Tree Patterns

3 patterns and 15 practice problems, each with a recall tip, a diagram, the theory and a Python template.

01

Tree - DFS (Pre/In/Post Order)

5 practice problems

Theory

  • Preorder: process node, then left, then right. Good for serialization.
  • Inorder: left, node, right. Gives sorted order for BSTs.
  • Postorder: left, right, node. Good for computing sizes / heights (bottom-up).
  • Recursive implementation is simplest. Iterative uses an explicit stack.

Code template

python
def dfs(node):
    if not node:
        return base_case
    left = dfs(node.left)
    right = dfs(node.right)
    # combine results (postorder logic)
    return combine(left, right, node.val)

# Iterative preorder
def preorder(root):
    if not root: return []
    stack, result = [root], []
    while stack:
        node = stack.pop()
        result.append(node.val)
        if node.right: stack.append(node.right)
        if node.left: stack.append(node.left)
    return result

Practice problems · 5

02

Tree - BFS (Level Order)

5 practice problems

Theory

  • Use a queue. Process all nodes at the current level before moving to the next.
  • Track level size at the start of each iteration: level_size = len(queue).
  • Useful for level order output, zigzag, right side view, minimum depth.
  • Time: O(n), Space: O(w) where w is the max width of the tree.

Code template

python
from collections import deque

def level_order(root):
    if not root: return []
    queue = deque([root])
    result = []
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node.val)
            if node.left: queue.append(node.left)
            if node.right: queue.append(node.right)
        result.append(level)
    return result
03

Tree - BST Properties

5 practice problems

Theory

  • Left subtree values < node < right subtree values.
  • Inorder traversal of a BST gives sorted order — use this to validate or find kth element.
  • Search / insert / delete: O(h) where h = log n for balanced, n for skewed.
  • Pass min/max bounds down during validation to check BST property.

Code template

python
def is_valid_bst(node, lo=float('-inf'), hi=float('inf')):
    if not node:
        return True
    if node.val <= lo or node.val >= hi:
        return False
    return (is_valid_bst(node.left, lo, node.val) and
            is_valid_bst(node.right, node.val, hi))

def kth_smallest(root, k):
    stack = []
    curr = root
    while stack or curr:
        while curr:
            stack.append(curr)
            curr = curr.left
        curr = stack.pop()
        k -= 1
        if k == 0:
            return curr.val
        curr = curr.right

Spotted a mistake on this page?

Wrong formula, broken animation or confusing wording. Tell us and we will fix it.