Traversal algorithms are essential for exploring nodes in a binary tree. Here's a breakdown of the most common methods:
1. Pre-order Traversal 📌
- Definition: Visit root → left subtree → right subtree
- Steps:
- Process the current node
- Recursively traverse left subtree
- Recursively traverse right subtree
- Example (Python):
def pre_order(root): if root: print(root.val) pre_order(root.left) pre_order(root.right)
2. In-order Traversal 📌
- Definition: Visit left subtree → root → right subtree
- Steps:
- Recursively traverse left subtree
- Process the current node
- Recursively traverse right subtree
- Example (Python):
def in_order(root): if root: in_order(root.left) print(root.val) in_order(root.right)
3. Post-order Traversal 📌
- Definition: Visit left subtree → right subtree → root
- Steps:
- Recursively traverse left subtree
- Recursively traverse right subtree
- Process the current node
- Example (Python):
def post_order(root): if root: post_order(root.left) post_order(root.right) print(root.val)
4. Level-order Traversal 📌
- Definition: Traverse nodes level by level (BFS)
- Steps:
- Use a queue to process nodes
- Start from root, enqueue left and right children sequentially
- Example (Python):
from collections import deque def level_order(root): if not root: return queue = deque([root]) while queue: node = queue.popleft() print(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right)
For a deeper understanding of binary tree fundamentals, check out our Binary Tree Introduction Guide. 📘