Binary tree preorder traversal solution explained

Binary tree preorder traversal lists each node before its subtrees: the node itself, then everything on its left, then everything on its right. Recursion gives it in five lines; interviewers usually then ask for an iterative version with an explicit stack, where you push the right child before the left so the left side is popped first. Both run in O(n) time and O(h) extra space, and Morris threading brings the extra space down to O(1).

By Published 7 min read

The problem in plain words

You get the root of a binary tree. Return a list of its values in preorder: write down a node's value the moment you arrive at it, then explore its entire left subtree the same way, then its entire right subtree. An empty tree gives an empty list. Nothing about the values matters; this is about visiting order only.

        6
       / \
      3   9
     / \    \
    1   5    11
       /
      4

Preorder: [6, 3, 1, 5, 4, 9, 11]
The tree used on this page, and its preorder

Read it as a trip around the outline of the tree, starting at the root and going down the left side first: each value is written down the first time you pass its node. 6 first, then down to 3, then 1. Back up to 3, down to 5 and its child 4. Then the right half: 9, then 11.

Why it gets asked

On its own, preorder is a warm-up. Interviewers use it to check three things quickly: that you can write a clean recursive walk, that you can convert recursion into a loop with your own stack (a skill that matters when recursion depth is a risk), and, for stronger candidates, whether you know any way to traverse without extra memory. Preorder is also the order used to copy a tree, serialize it, and print a directory listing with folders before their contents.

Baseline: recursion

The definition is recursive, so the first solution is too. Record the node, recurse left, recurse right. Each node is visited once, so time is O(n). Extra space is the call stack, O(h) for height h: about log n on a balanced tree, but n on a tree that is a single long chain.

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def preorder_recursive(root):
    out = []

    def visit(node):
        if node is None:
            return
        out.append(node.val)   # root first
        visit(node.left)
        visit(node.right)

    visit(root)
    return out
Python, recursive. O(n) time, O(h) call stack.

This is accepted almost everywhere, but say the limitation out loud: CPython's default recursion limit is around a thousand frames, so a degenerate tree of a few thousand nodes raises an error. That is the cue for the iterative version.

Iterative: an explicit stack

Replace the call stack with a list you control. Start with the root on the stack. Pop a node, record its value, then push its right child and its left child, in that order. Because a stack is last in, first out, the left child comes off next, which is exactly what preorder needs. The right child waits underneath until the whole left subtree has been processed.

def preorder_iterative(root):
    out = []
    stack = [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.right:              # pushed first, so popped after the left side
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    return out
Python, explicit stack. O(n) time, O(h) stack in the worst case.
function preorderIterative(root) {
  const out = [];
  const stack = root ? [root] : [];
  while (stack.length > 0) {
    const node = stack.pop();
    out.push(node.val);
    if (node.right) stack.push(node.right); // right waits underneath
    if (node.left) stack.push(node.left);
  }
  return out;
}
JavaScript, explicit stack. Works on chains of tens of thousands of nodes.

Trace it on the example. The stack holds [6]. Pop 6, record it, push 9 then 3. Pop 3, record, push 5 then 1. Pop 1 (a leaf). Pop 5, record, push 4. Pop 4. Pop 9, record, push 11. Pop 11. The output is 6, 3, 1, 5, 4, 9, 11.

Follow-up: O(1) extra space with Morris traversal

Morris traversal avoids any stack by temporarily rewiring the tree. When a node has a left subtree, find that subtree's rightmost node, its inorder predecessor. If the predecessor's right pointer is empty, this is the first arrival: record the node (preorder records on the way down), point the predecessor's right pointer back at the node, and move left. When the walk later follows that thread back up, the predecessor's right pointer already points at the node; remove the thread and move right. Nodes without a left child are recorded and left behind immediately.

def preorder_morris(root):
    out = []
    node = root
    while node:
        if node.left is None:
            out.append(node.val)
            node = node.right
            continue
        pred = node.left                      # rightmost node of the left subtree
        while pred.right and pred.right is not node:
            pred = pred.right
        if pred.right is None:                # first arrival: record, thread, go left
            out.append(node.val)
            pred.right = node
            node = node.left
        else:                                 # back through the thread: undo it, go right
            pred.right = None
            node = node.right
    return out
Python, Morris preorder. O(n) time, O(1) extra space; the tree is restored by the end.
function preorderMorris(root) {
  const out = [];
  let node = root;
  while (node) {
    if (!node.left) {
      out.push(node.val);
      node = node.right;
      continue;
    }
    let pred = node.left;
    while (pred.right && pred.right !== node) pred = pred.right;
    if (!pred.right) {
      out.push(node.val);
      pred.right = node; // temporary thread back up
      node = node.left;
    } else {
      pred.right = null; // restore the tree
      node = node.right;
    }
  }
  return out;
}
JavaScript, Morris preorder.

Each edge is walked a bounded number of times while finding predecessors, so the total stays O(n). The cost is that the tree is modified while the loop runs, which is unsafe if another thread reads it at the same time. Mention that trade-off if you offer this version.

Complexity

n nodes, height h
ApproachTimeExtra spaceNote
RecursionO(n)O(h) call stackShortest; deep trees can hit the recursion limit
Explicit stackO(n)O(h)The answer most interviewers expect
Morris threadingO(n)O(1)Temporarily changes pointers; restores them
n nodes, height h. Scroll sideways on a small screen.

Edge cases to test

  • An empty tree: return an empty list, and never push None onto the stack.
  • A single node.
  • A tree that only has left children, and one that only has right children.
  • A node with only a right child, like 9 in the example.
  • Duplicate values. The traversal must not depend on values at all.

Common mistakes

  • Pushing the left child before the right one, which produces root, right, left.
  • Recording a node when it is pushed instead of when it is popped. In this loop the two happen to differ in order.
  • In Morris traversal, recording the node on the second arrival; that gives inorder, not preorder.
  • Forgetting to remove the thread, which leaves a cycle in the caller's tree.
  • Returning inside the recursive helper and losing the shared output list.

How to explain it out loud

Fictional example

A short spoken walkthrough
Candidate
Preorder means I write a node down as soon as I reach it, then do its left side, then its right side. Recursively that is three lines.
Candidate
To avoid deep recursion I will use my own stack. I pop a node, record it, and push right before left, so left comes out first.
Candidate
Every node is pushed and popped once, so it is linear time, and the stack holds at most about one root-to-leaf path of pending right children.
Interviewer
Can you do it without the stack?
Candidate
Yes, with Morris threading: I link each left subtree's rightmost node back to its ancestor so I can climb back without memory, and I remove each link on the way back.

The mirror-image ordering, children before parent, is Binary Tree Postorder Traversal, and it reuses this stack trick in reverse. Postorder plus inorder is enough to rebuild a whole tree, which is the subject of Construct Binary Tree from Inorder and Postorder. For breadth-first order instead, see Binary Tree Level Order Traversal, and the graph traversal patterns guide puts all of these on one page.

Practicing with Natively

When you rehearse tree problems, Natively can read the problem and the drawing from a screenshot on Mac or Windows, show you the recursive and stack versions side by side, and explain why the right child goes on the stack first. It also transcribes your practice session, so you can check afterwards whether you mentioned the recursion limit before being asked.

Questions people ask

What is preorder traversal of a binary tree?

Visiting each node before its subtrees: the node itself, then its whole left subtree, then its whole right subtree.

How do you do preorder traversal without recursion?

Use a stack that starts with the root. Pop a node, record its value, then push its right child and then its left child, so the left child is popped next.

What is the time and space complexity of preorder traversal?

O(n) time. Extra space is O(h) for the recursion or the stack, where h is the tree's height, or O(1) with Morris traversal.

Why push the right child before the left in iterative preorder?

A stack returns the last item pushed first. Pushing right then left makes the left child come out next, so the left subtree is finished before the right one starts.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP