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 TreePre-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
- If the current node is null, return (base case).
- Visit (process) the current node.
- Recursively traverse the left subtree.
- Recursively traverse the right subtree.
Pre-order Worked Example
Input: Tree: root(2), left(1), right(3)
- Visit root: 2
- Go left to node 1: visit 1
- Go right to node 3: visit 3
Output: 2, 1, 3
Press ▶ Run to watch it step by step.
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 traverseBehind 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.