Preorder Traversal: Definition, Example, and Use Cases
root node, then recursively visit the left subtree, followed by the right subtree. It is a depth-first traversal method used to process nodes in a specific order.How It Works
Preorder traversal visits nodes in a tree starting from the root node first. Imagine you are exploring a family tree: you first meet the parent, then you check their left child, and after finishing that branch, you move to the right child. This way, you always handle the current node before its children.
This method is called "depth-first" because it goes deep into one branch before moving to another. The order is always: visit the node, then visit left subtree, and finally visit right subtree. This helps when you want to copy a tree or evaluate expressions stored in a tree.
Example
This example shows preorder traversal on a simple binary tree using Python. It prints nodes in the order they are visited.
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def preorder_traversal(node): if node is None: return print(node.value, end=' ') preorder_traversal(node.left) preorder_traversal(node.right) # Create tree: # 1 # / \ # 2 3 # / \ # 4 5 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) preorder_traversal(root)
When to Use
Preorder traversal is useful when you need to process or copy a tree starting from the root before its children. For example, it is used in:
- Saving a tree structure to a file (serialization)
- Evaluating prefix expressions in expression trees
- Creating a copy of the tree
- Generating prefix notation in compilers
It helps when the order of processing the root before children matters.
Key Points
- Preorder traversal visits the root node first, then left subtree, then right subtree.
- It is a depth-first traversal method.
- Useful for copying trees and prefix expression evaluation.
- Can be implemented easily with recursion.