Binary Tree Preorder Traversal

EasyTrees · DFS (Pre-order)🧩 Tree DFSLeetCode #144 ↗Updated

Problem

Return the values of a binary tree in pre-order: visit the node itself first, then its entire left subtree, then its entire right subtree (Node → Left → Right).
Input[1,null,2,3]Output[1,2,3]
Input[1,2,3,4,5,null,8,null,null,6,7,9]Output[1,2,4,5,6,7,3,8,9]
Input[]Output[]

0 ≤ nodes ≤ 100  ·  -100 ≤ Node.val ≤ 100  ·  Follow-up: recursion is trivial — do it iteratively.

Try it yourself

Java
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The only hard part of DFS is finding the way back after a left subtree. Recursion and stacks remember it in O(h) memory; Morris instead plants a temporary pointer from the left subtree's rightmost node back to the current node.
PatternTree DFS

Instinct If the answer for a node can be built from the answers of its left and right subtrees, write one recursive function and trust it on the children.

Memory hack Ask the kids, then decide - each child reports up, the parent combines, and a global variable keeps the best "bend" seen so far.

Open the Tree DFS guide →

Approaches

Brute ForceRecursive DFS

Time O(n)Space O(h)

Direct translation of the definition: record the node, recurse left, recurse right. The call stack remembers where to return, using one frame per level of depth h.

Java
public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    preorder(root, res);
    return res;
}
private void preorder(TreeNode node, List<Integer> res) {
    if (node == null) return;
    res.add(node.val);       // Node
    preorder(node.left, res);  // Left
    preorder(node.right, res); // Right
}

Clearest code, but O(h) call stack (O(n) when skewed) and not what the follow-up wants.

At a glance

LevelApproachTimeSpace
Brute ForceRecursive DFSO(n)O(h)
BetterIterative with Explicit StackO(n)O(h)
OptimalMorris Traversal (Threaded Tree)O(n)O(1)
Common pitfalls
  • Stack version: pushing left before right → you get Node-Right-Left order.
  • Morris: forgetting to remove the thread leaves a corrupted (cyclic) tree.
  • Morris: recording the node on the second visit (that is in-order, not pre-order).
Interview tips
  • Write the 4-line recursion first, then convert it to a stack for the follow-up.
  • Explain why right is pushed first (LIFO).
  • Mention Morris for O(1) space and note it mutates the tree temporarily.
Pattern
DFS order = when you record the node → pre (before children), in (between), post (after); stack or Morris replace recursion.
My notes saved in this browser