Given the root of a binary tree, return the preorder traversal of its nodes' values — visit the node first, then the left subtree, then the right subtree.
The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [1, null, 2, 3] Output: [1, 2, 3] Record 1, then its left subtree (empty), then its right subtree yielding 2 then 3.
Input: root = [] Output: [] An empty tree has no nodes.
- The number of nodes is in the range [0, 100] - -100 <= Node.val <= 100
Preorder means node, left, right — record a node the moment you reach it, then descend. The recursive version is a direct transcription; the iterative version uses a stack, pushing the right child before the left so the left comes off first.
“What is preorder exactly?”
The current node, then its left subtree, then its right subtree.
“Where is preorder used?”
Copying/serializing a tree — you emit a node before its children, so rebuilding is straightforward.
Preorder is node, left, right, so I record the node first, then recurse left, then recurse right.
Iteratively I use a stack and push the right child before the left, so the left is processed first.
Worked example — tree [1, null, 2, 3] (1 with right child 2, whose left child is 3)
1
\
2
/
3
preorder: 1 -> left of 1 (none) -> right subtree of 1
in that subtree: 2 -> 3
result: [1, 2, 3]
Record on arrival, before descending — that's what distinguishes it from inorder and postorder.
A stack is LIFO, so to pop the left child first you must push it last — push right, then left.
Every node is visited once (O(n)); the stack holds at most O(height) nodes.
| Iterative (explicit stack) | Recursive | |
|---|---|---|
| Idea | Pop, record, push right then left | record; dfs(left); dfs(right) |
| Time | O(n) | O(n) |
| Space | O(height) | O(height) |
Both are O(n); the recursive form is the clearest, the iterative form avoids the call stack. Full code is in the Approaches selector below.
Key takeaway
Preorder = node, left, right. Record the node on arrival, then recurse left and right — or use a stack, pushing the right child before the left. O(n) time, O(height) space.
preorder(node):
if node is null: return
visit(node)
preorder(node.left)
preorder(node.right)