Preorder Traversal is an important tree traversal technique used in Data Structures and Algorithms (DSA). It follows the order Root, Left, Right, which means the root node is visited first, followed by the left subtree and then the right subtree. Preorder traversal is a type of Depth First Search (DFS) and is commonly used in binary trees, tree copying, serialization, and expression tree processing. Understanding this technique helps beginners learn how tree traversal works and prepare for coding interviews.
Table of Contents
What Is Preorder Traversal?
Preorder Traversal is a tree traversal technique in which the root node is visited before its left and right subtrees.
It follows a specific order: Root → Left → Right
Preorder traversal belongs to Depth First Search (DFS), where the algorithm explores one branch deeply before moving to another branch.
In this technique:
- First, visit the root node.
- Next, traverse the left subtree.
- Finally, traverse the right subtree.
The same process is applied recursively to every subtree until all nodes have been visited.
Preorder traversal is commonly used with binary trees, but it can also be applied to other rooted trees.
How Does Preorder Traversal Work?
Preorder traversal starts from the root node and processes each node before visiting its children.
For every node, the algorithm performs three actions:
- Visit the current node.
- Process its left child and the entire left subtree.
- Process its right child and the entire right subtree.
If a node does not have a left or right child, the algorithm skips that missing subtree and continues.
The process stops when all nodes have been visited.
Steps of Preorder Traversal
The following steps explain how to perform preorder traversal:
- Start from the root node.
- Check whether the current node exists.
- Visit the current node and process its value.
- Recursively traverse the left subtree.
- Recursively traverse the right subtree.
- Continue until there are no more nodes to visit.
Important Rule: Always visit the root before its left and right subtrees.
Preorder Traversal Example
Consider a binary tree containing the following values:
- Root node: 10
- Left child: 20
- Right child: 30
- Children of node 20: 40 and 50
Applying preorder traversal follows the Root → Left → Right order.
The visiting sequence is: 10 → 20 → 40 → 50 → 30
Explanation:
- First, visit node 10 because it is the root.
- Next, visit node 20, the left child of 10.
- Then, visit node 40, the left child of 20.
- Visit node 50, the right child of 20.
- Finally, visit node 30, the right child of 10.
The final preorder traversal sequence is:
10, 20, 40, 50, 30
Preorder Traversal Using Recursion
Recursion is one of the simplest ways to implement preorder traversal. A recursive function calls itself to process the left and right subtrees.
JavaScript Example:
// This program performs preorder traversal using recursion.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function preorder(root) {
if (root === null) {
return;
}
console.log(root.value);
preorder(root.left);
preorder(root.right);
}
const root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
preorder(root);
Output:
10
20
40
50
30
Explanation:
- The Node class creates individual tree nodes.
- Each node stores a value and references to its left and right children.
- The preorder() function first checks whether the current node is null.
- If the node exists, its value is printed.
- The function then calls itself for the left subtree.
- Finally, it calls itself for the right subtree.
The recursive function continues until every node has been visited.
Why Is Recursion Used?
A tree naturally contains smaller subtrees. Recursion makes it easier to apply the same traversal process to each subtree without writing separate code for every level.
Preorder Traversal Using Iteration
Preorder traversal can also be implemented without recursion by using a stack data structure.
A stack follows the Last In, First Out (LIFO) principle.
To maintain the Root → Left → Right order, we push the right child first and the left child second. This ensures that the left child is processed first.
Steps:
- Create an empty stack.
- Insert the root node into the stack.
- Remove the top node from the stack.
- Visit the removed node.
- Push its right child if it exists.
- Push its left child if it exists.
- Repeat until the stack becomes empty.
JavaScript Example:
// This program performs preorder traversal using an iterative stack.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function preorderIterative(root) {
if (root === null) {
return;
}
const stack = [root];
while (stack.length > 0) {
const current = stack.pop();
console.log(current.value);
if (current.right !== null) {
stack.push(current.right);
}
if (current.left !== null) {
stack.push(current.left);
}
}
}
const root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
preorderIterative(root);
Output:
10
20
40
50
30
Explanation:
The stack initially contains the root node 10.
- Remove and visit 10.
- Push 30 first and then 20.
- Remove and visit 20.
- Push 50 first and then 40.
- Visit 40 and then 50.
- Finally, visit 30.
The stack ensures that the left subtree is processed before the right subtree.
Important Point: Although the right child is pushed first, it is processed after the left child because a stack follows the LIFO principle.
Preorder Traversal in a Binary Search Tree
Preorder traversal can also be performed on a Binary Search Tree (BST).
A Binary Search Tree is a special binary tree in which smaller values are generally stored in the left subtree and larger values in the right subtree.
Preorder traversal visits the root first, followed by the left and right subtrees, regardless of whether the tree is a BST.
JavaScript Example:
// This program performs preorder traversal of a Binary Search Tree.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function insert(root, value) {
if (root === null) {
return new Node(value);
}
if (value < root.value) {
root.left = insert(root.left, value);
} else if (value > root.value) {
root.right = insert(root.right, value);
}
return root;
}
function preorder(root) {
if (root === null) {
return;
}
console.log(root.value);
preorder(root.left);
preorder(root.right);
}
let root = null;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 70);
root = insert(root, 20);
root = insert(root, 40);
preorder(root);
Output:
50
30
20
40
70
Explanation:
The traversal starts at the root node 50. It then visits the left subtree containing 30, 20, and 40. Finally, it visits the right subtree containing 70.
Unlike inorder traversal, preorder traversal does not produce sorted output from a Binary Search Tree.
Applications of Preorder Traversal
Preorder traversal is useful in several computer science applications.
- Tree Copying: It can be used to create a copy of a tree by processing the parent before its children.
- Tree Serialization: Preorder traversal can store a tree in a sequence. Null markers are needed to preserve the exact tree structure.
- Expression Trees: It can generate prefix expressions from expression trees.
- File Systems: It can help process a directory before exploring its subdirectories.
- Tree Processing: It is useful when parent nodes need to be processed before their child nodes.
- Tree Reconstruction: Preorder traversal, combined with inorder traversal for a suitable binary tree with distinct values, can help reconstruct the tree.
Time and Space Complexity
Time and space complexity describe how efficiently an algorithm uses processing time and memory. Let N represent the total number of nodes in the tree, and H represent its height.
| Complexity | Recursive Method | Iterative Method |
|---|---|---|
| Time Complexity | O(N) | O(N) |
| Auxiliary Space | O(H) | O(N) in the worst case |
Time Complexity: O(N)
Preorder traversal visits every node exactly once. Therefore, the time complexity is O(N).
Space Complexity:
- Recursive traversal uses O(H) space for the function call stack.
- Iterative traversal uses a stack that can store up to O(N) nodes in the worst case.
- For a balanced binary tree, the recursive call stack generally requires O(log N) space.
- For a highly unbalanced tree, recursive traversal can require O(N) space.
Advantages of Preorder Traversal
Some important advantages of preorder traversal are:
- It is simple to understand and implement.
- It processes the root node before its children.
- It supports tree copying and serialization.
- It can be implemented using recursion or iteration.
- It visits every node exactly once.
- It is useful for generating prefix expressions from expression trees.
Common Mistakes to Avoid
- Incorrect Traversal Order: Always follow Root → Left → Right.
- Missing Base Condition: Check whether the current node is null before accessing its value.
- Wrong Stack Order: In iterative traversal, push the right child before the left child.
- Forgetting Empty Trees: Handle cases where the root node is null.
- Confusing Preorder with Inorder: Preorder visits the root first, whereas inorder visits the root between the left and right subtrees.
Frequently Asked Questions
1. What is preorder traversal?
Preorder traversal is a tree traversal technique that visits the root node first, followed by the left subtree and then the right subtree.
2. What is the order of preorder traversal?
The order is Root → Left → Right.
3. Which data structure is used for iterative preorder traversal?
A stack is used to perform iterative preorder traversal.
4. What is the time complexity of preorder traversal?
The time complexity is O(N), where N is the total number of nodes in the tree.
5. Does preorder traversal give sorted output in a Binary Search Tree?
No. Preorder traversal visits the root before its subtrees and does not generally produce sorted output. Inorder traversal produces sorted output for a standard Binary Search Tree.
0 Comments