How tree traversal works
Preorder records a node before recursing into its children. Inorder records it between the left and right calls — which, on a binary search tree, produces the values in sorted order. Postorder, not shown here, records it after both. Level-order is a different kind of traversal: it uses a queue instead of recursion and visits the tree row by row.
The example tree has root 4, children 2 and 6, and 2’s children 1 and 3. Inorder gives [1, 2, 3, 4, 6], preorder [4, 2, 1, 3, 6] and level-order [4, 2, 6, 1, 3].
What to watch for when it runs
- The output list grows one value at a time, so you can see exactly when each node is visited.
- During the recursive traversals the call stack mirrors the path from the root to the current node.
- During level-order, the queue holds the next row of the tree.
Time and space complexity
- Time
- O(n) each
- Space
- O(h) for recursion, O(w) for level-order
h is the tree’s height and w its widest level. Every node is visited exactly once by every traversal.