Binary Tree · Traversal

Preorder Traversal

Visit nodes in Root → Left → Right order. The root is always processed first, before any subtree.

RecursionDFSInterview Essential

Key concepts at a glance — for those who already know the basics.

Problem Statement

Binary Tree Preorder Traversal

Given the root of a binary tree, return the preorder traversal of its node values.
Example 1

Input: root = [1, null, 2, 3]

Output: [1, 2, 3]

Tree: 1 → right child 2, left child of 2 is 3.

Example 2

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].
01

The Rule

Root → Left → Right

The current node is always visited before exploring any of its children.

02

How to Think

1

Visit (record) the current node immediately

Before going anywhere — this is what makes it 'pre' order.

2

Recurse into the left subtree

Handle the entire left branch, root-first, the same way.

3

Recurse into the right subtree

Apply Root → Left → Right recursively to the right branch.

03

Code

solution.py
def preorder(node, result):
if node is None: return # base case
result.append(node.val) # 1. root ← first!
preorder(node.left, result) # 2. left
preorder(node.right, result)# 3. right
04

Complexity

Time

O(n)

Every node visited once.

Space

O(h)

Stack depth = tree height.

05

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.

Open Visualizer