← Tree Traversal

Micro-Drill #201 — Iterative inorder with stack

Tree Traversal Target: 10s

Push all left children, pop and process, go right. The fundamental iterative tree pattern.

def inorder(root):
    res, stack = [], []
    cur = root
    while cur or stack:
        while cur:           # go left as far as possible
            stack.append(cur)
            cur = cur.left
        cur = stack.pop()    # process node
        res.append(cur.val)
        cur = cur.right      # go right
    return res

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #200 Micro #202 →