Preorder Traversal Visualization & Animation
A preorder traversal first visits the node, then visits the left child (including its entire subtree), and finally visits the right child (including its entire subtree).
## What is it?
Preorder traversal visits every node in a binary tree in **Root → Left → Right** order. The root is always visited **first**, before any children — making it ideal for copying or serializing a tree structure.
## How it works
- **Process (visit)** the current node first
- Recursively visit the **left** subtree
- Recursively visit the **right** subtree
```
preorder(node):
if node is null: return
visit(node) ← add to result first
preorder(node.left)
preorder(node.right)
```
## When to use
- **Copy / clone** a tree — inserting preorder output into a new BST reconstructs the same structure
- **Serialize** a tree to a string (with null markers, it is fully reversible)
- Print or display hierarchical structures (directory trees, XML/HTML DOM)
- Evaluate prefix (Polish notation) expressions
## Key Points
- The first element in preorder output is always the root
- Combined with inorder output, preorder uniquely identifies a binary tree
- Recursive call stack depth = O(h)
- Used in compilers to generate prefix notation from expression trees
Category: algorithms
Difficulty: beginner
Time Complexity: O(n)
Space Complexity: O(h)
View Preorder Traversal Visualization