High interview relevanceRoadmap: Intermediate
TimeO(n)
SpaceO(h) for depth-first orders

Why it costs this much

Every node is visited exactly once, and the recursion stack holds only one root-to-node path.

Code

def inorder(node, out):
    if node:
        inorder(node.left, out)
        out.append(node.val)        # each node is appended once: O(n)
        inorder(node.right, out)    # stack depth never exceeds the height h

Common pitfalls

Space is O(h), which is O(n) on a skewed tree. Level-order traversal uses O(w) space for the widest level w.

Operation by operation

OperationBestAverageWorstSpace
Tree traversal (in-order, pre-order, post-order, level-order)O(n)O(n)O(n)O(h) stack; O(w) for level-order

Tree traversal (in-order, pre-order, post-order, level-order). Visits each node once. h is height, w is the widest level. A skewed tree has h = n, so the recursion stack is O(n).

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list