Binary Tree Preorder Traversal (Recursive)
Binary Tree Preorder Traversal (Recursive) is a easy trees & bst problem solved with the recursion pattern.
The best approach, iterative (stack), runs in O(n) time and O(h) space.
Below are 2 approaches in Java, from recursive dfs up.
Problem
Return the preorder traversal (node, left, right) of a binary tree.
Examples
Example 1
- Input
root = [4, 2, 6, 1, 3]- Output
[4, 2, 1, 3, 6]
Example 2
- Input
root = [1, null, 2]- Output
[1, 2]
Constraints
- The tree has
0to100nodes.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Recursive DFS | O(n) | O(h) |
| Iterative (stack) | O(n) | O(h) |
1Recursive DFS
O(n)O(h)Record the node before visiting its children.
- if node == null return.
- add(node.val); preorder(left); preorder(right).
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
preorder(root, out);
return out;
}
private void preorder(TreeNode node, List<Integer> out) {
if (node == null) return;
out.add(node.val);
preorder(node.left, out);
preorder(node.right, out);
}
}2Iterative (stack)
O(n)O(h)Pop a node, record it, then push its right child before its left so the left is processed first.
- Push root; while the stack is not empty: pop, add, push right, push left.
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
if (root == null) return out;
Deque<TreeNode> st = new ArrayDeque<>();
st.push(root);
while (!st.isEmpty()) {
TreeNode n = st.pop();
out.add(n.val);
if (n.right != null) st.push(n.right);
if (n.left != null) st.push(n.left);
}
return out;
}
}Edge cases to test
- Empty tree
Hints
Hint 1
Preorder = root first, then left, then right. It is the order used to copy or serialize a tree.
FAQ
What is the best time complexity for Binary Tree Preorder Traversal (Recursive)?
Iterative (stack) runs in O(n) time and O(h) extra space.
Which pattern does Binary Tree Preorder Traversal (Recursive) use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive), Binary Tree Inorder Traversal (Iterative).
Is there a brute force solution for Binary Tree Preorder Traversal (Recursive)?
Yes. Recursive DFS takes O(n) time and O(h) space. Record the node before visiting its children.
Which edge cases should I test for Binary Tree Preorder Traversal (Recursive)?
Empty tree.