DrawCode Algorithm Visualizer • Tree • Easy

Preorder Traversal (Iterative)

Tags: Tree, DFS, Stack, Traversal

1. One-Liner

Iterative preorder visits root → left → right using a stack, pushing children so left is processed before right.


2. The Problem It Solves

You need a DFS order that lists the root before subtrees (copying trees, prefix expressions, serialization) without recursion—useful when call depth is limited or you want an explicit frontier.


3. The Core Idea

Pop the current node, record its value, then push right then left so the stack yields left on top next. This preserves preorder while using LIFO instead of the function-call stack.


4. How It Works (Step-by-Step)

StepAction
1Push root on stack (if not null).
2While stack not empty: pop node, append its value.
3Push right child, then left child (if exist).
4Next pop visits left subtree first—preorder.
5Stop when stack empty.

5. Dry Run Example

Tree: root 1, children 2 (L), 3 (R).

PopStack after pushOutput
1[3,2][1]
2[3][1,2]
3[][1,2,3]

6. Key Properties

PropertyDetail
OrderRoot before its subtrees
SpaceO(h) stack typical
MirrorSwap push order for “root-right-left”

7. Where It Is Used

AreaUse
SerializationSave tree to file stream
CloningCreate nodes in parent-first order
ParsingExpression tree prefix evaluation

8. Interview Tips

Right before left on stack is the classic gotcha. Contrast with inorder (no simple single-stack pop order). Know Morris preorder as O(1) space follow-up.


9. Comparison with Other Algorithms

VariantOrderTypical stack
Preorder iterRoot-L-RNode stack
Inorder iterL-Root-RDescend-left style
BFS levelLevel-wiseQueue

10. Complexity

----
TimeO(n)
SpaceO(h) worst O(n)

Implementation Example (PYTHON)

def preorder_iterative(root):
    if not root:
        return []
    out, stack = [], [root]
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    return out

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer