Data Structures · Visualization

Binary Tree: Pre-order

Binary Tree

Pre-order traversal visits the current node first, then the left subtree, then the right subtree (Node, Left, Right). Time: O(n). Space: O(h) for the recursion stack.

Big-O: Traversals visit every node exactly once: O(n).

Binary Tree: Pre-order

Binary Tree

Pre-order traversal visits the current node first, then the left subtree, then the right subtree (Node, Left, Right). Because the root always comes first, this traversal is ideal for recreating (serializing) the tree's structure or copying a tree.

How Pre-order Works

  1. If the current node is null, return (base case).
  2. Visit (process) the current node.
  3. Recursively traverse the left subtree.
  4. Recursively traverse the right subtree.

Pre-order Worked Example

Input: Tree: root(2), left(1), right(3)

  1. Visit root: 2
  2. Go left to node 1: visit 1
  3. Go right to node 3: visit 3

Output: 2, 1, 3

Binary Tree: Introduction
A hierarchy of nodes where each node has at most two children — usually called "left" and "right".
45
20
10
30
40
65
50
60
70
80
Active Result
Binary Tree: Introduction
Press ▶ Run to watch it step by step.
Python · Binary Trees in Code
def preorder(n):
    if not n:
        return
    print(n.val, end=" ")   # root FIRST
    preorder(n.left)        # then left
    preorder(n.right)       # then right

# root -> left -> right
# example: pre-order traverse
Input: Tree: root(2), left(1), right(3)

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Pre-order Time & Space Complexity

TimeO(n)
SpaceO(h) for the recursion stack

When to Use Pre-order

  • Copying or serializing a tree's exact structure
  • Creating a prefix expression from an expression tree
  • Exploring a directory structure starting from the top folder

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.