Preorder Traversal
Visit nodes in Root → Left → Right order. The root is always processed first, before any subtree.
Key concepts at a glance — for those who already know the basics.
Problem Statement
Binary Tree Preorder Traversal
Input: root = [1, null, 2, 3]
Output: [1, 2, 3]
Tree: 1 → right child 2, left child of 2 is 3.
Input: root = [1, 2, 3, 4, 5, 6, 7]
Output: [1, 2, 4, 5, 3, 6, 7]
Perfect binary tree — root, left subtree, right subtree.
Constraints
- The number of nodes in the tree is in the range [0, 100].
- Each node's value is in the range [-100, 100].
The Rule
Root → Left → Right
The current node is always visited before exploring any of its children.
How to Think
Visit (record) the current node immediately
Before going anywhere — this is what makes it 'pre' order.
Recurse into the left subtree
Handle the entire left branch, root-first, the same way.
Recurse into the right subtree
Apply Root → Left → Right recursively to the right branch.
Code
Complexity
Time
O(n)
Every node visited once.
Space
O(h)
Stack depth = tree height.
Interview Uses
Serialize a binary tree
Preorder output + nulls fully reconstructs the tree.
Copy / clone a tree
Root-first creation means children can be attached right after.
Print directory structure
Preorder mirrors how file systems display nested folders.
Find a path to a node
Root-to-leaf path tracking is naturally preorder.
Ready to see it in action?
Step through the visualizer to watch the algorithm state update live.