data structuresalgorithmstreesbinary treesdepth-first searchprogrammingcomputer science
Pre order traversal is a depth-first tree traversal strategy that visits each node before its subtrees. In binary trees, the canonical order is: visit the root, traverse the left subtree, then traverse the right subtree. In general trees (n-ary), you visit the node, then recursively visit each child from left to right. It is widely used for tasks like tree serialization, copying structures, prefix notation of expression trees, and generating root-to-leaf paths. It runs in linear time with space proportional to the tree height.
What Is Pre Order Traversal?
Pre order traversal is a systematic way to visit all nodes in a tree using a depth-first strategy. The key idea is to process ("visit") each node before exploring its children.
Binary tree order: Root, Left subtree, Right subtree (often written as R-L-R).
N-ary tree order: Visit node, then visit children from left to right.
Example
A
/ \
B C
/ \ \
D E F
Pre order sequence: A, B, D, E, C, F
Algorithm (High Level)
Visit the current node (process its value).
Recursively traverse the left (or first) child subtree.
Recursively traverse the right (or remaining) child subtree.
For an iterative version, use an explicit stack: push the root, pop a node, visit it, then push its children in reverse order of the desired visit so the leftmost child is processed next.
Recursive Implementation
Binary Tree (Python)
def preorder_recursive(root):
result = []
def dfs(node):
if not node:
return
result.append(node.val) # visit
dfs(node.left)
dfs(node.right)
dfs(root)
return result
N-ary Tree (Pseudocode)
function preorder(node):
if node is null: return
visit(node)
for child in node.children:
preorder(child)
Iterative Implementation (Using a Stack)
Binary Tree (Python)
def preorder_iterative(root):
if not root:
return []
stack = [root]
out = []
while stack:
node = stack.pop()
out.append(node.val)
# Push right first so left is processed next
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return out
Binary Tree (JavaScript)
function preorder(root) {
if (!root) return [];
const res = [];
const stack = [root];
while (stack.length) {
const node = stack.pop();
res.push(node.val);
if (node.right) stack.push(node.right);
if (node.left) stack.push(node.left);
}
return res;
}
Complexity
Time: O(n), where n is the number of nodes (each node is visited once).
Space: O(h), where h is the height of the tree (due to recursion or the explicit stack). In the worst case (skewed tree), h = O(n); in a balanced tree, h = O(log n).
Common Uses
Serialization and cloning of trees (prefix form), often with null markers for missing children.
Evaluating or printing expression trees in prefix (Polish) notation.
Generating root-to-leaf paths or performing side-effectful visits (e.g., setting indexes, computing sizes before visiting children).
Precomputing or exporting hierarchical structures (menus, file systems, ASTs).
Relationship to Other Traversals
In order (binary trees only): Left, Root, Right — often yields sorted order in a BST.
Post order: Left, Right, Root — useful for deleting trees, computing subtree values, or evaluating postfix expressions.
Breadth-first (level order): Visits nodes level by level, not depth-first.
Variations and Nuances
N-ary trees: Visit node, then children in order.
Threaded or implicit trees: Pre order still applies; child access differs.
Iterative vs recursive: Iterative avoids recursion depth limits; recursive is often simpler.
Pitfalls and Tips
Always handle null roots gracefully.
For iterative versions, push the right child before the left to maintain left-first visitation.
Be mindful of recursion depth on very deep trees; consider iterative approach where needed.
When serializing, include markers for missing children to support unambiguous reconstruction.
Quick Practice
Write a function to return the pre order sequence of a binary tree.
Modify it to work for an n-ary tree with a children list.
Serialize a binary tree with pre order using a sentinel (e.g., #) for nulls, then write the corresponding deserializer.
In an iterative pre-order traversal of a binary tree using a stack, which push order ensures left subtree nodes are visited before right subtree nodes?
Including explicit null markers, a pre-order traversal can serialize a binary tree in a way that allows unambiguous reconstruction of the original tree.
In the worst case of a skewed binary tree with n nodes, what is the auxiliary space complexity of an iterative pre-order traversal that uses an explicit stack?
Consider this binary tree: the root 10 has left child 5 and right child 12; node 5 has left child 3 and right child 7; node 7 has right child 8; node 12 has right child 15. What is the pre-order traversal sequence?
Next Topic
used_by
0.92
Tree Construction From Preorder Inorder
Binary tree reconstruction uses the preorder sequence (with inorder) to pick the root at each step and partition left/right subtrees, enabling unique reconstruction.
used_by
0.9
Tree Serialization
Tree serialization schemes often encode nodes in preorder (root-first) to capture structure deterministically; preorder plus null markers enables lossless reconstruction.
used_by
0.9
Expression Tree Evaluation
Tree serialization schemes often output nodes in pre-order (with null markers) to capture structure and enable accurate deserialization.
used_by
0.9
Dfs Applications
Pre-order provides a root-first sequence that naturally encodes tree structure and values, so many serialization schemes traverse nodes in pre-order to write out trees.
used_by
0.9
N Ary Tree Traversal
Pre-order traversal provides a deterministic node-before-children order to linearize trees into sequences that can be stored/transmitted and later reconstructed.
used_by
0.88
Binary Search Tree Operations
Tree serialization schemes often output nodes in pre-order (with null markers or length metadata) to enable unambiguous reconstruction.
related_to
0.86
Post Order Traversal
A complementary depth-first traversal that visits all children before the node; commonly learned alongside preorder to compare ordering and applications like deletion and expression evaluation.
used_by
0.82
In Order Traversal
Pre-order traversal yields a node-first sequence that can be written to a stream with null markers or child counts, enabling faithful reconstruction of the original tree.
used_by
0.82
Root To Leaf Paths
Pre-order visits a node before its children, making it natural to maintain a running path and record it at leaves to enumerate all root-to-leaf paths.
depends_on
0.68
Iterative Traversal Patterns
Implementing pre-order traversal without recursion relies on iterative traversal patterns such as using an explicit stack and loop invariants to simulate the call stack.