What is Inorder Traversal: Explanation and Example
left-node-right order is commonly used to get nodes in sorted order for binary search trees.How It Works
Inorder traversal visits nodes in a binary tree by following a simple rule: first, go to the left child, then visit the current node, and finally go to the right child. Imagine reading a book where you first look at the left page, then the center page, and then the right page. This order ensures that you see all nodes in a sorted sequence if the tree is a binary search tree.
This method uses recursion or a stack to remember where it left off when exploring the left side before moving to the current node and then the right side. It is like exploring a family tree by first checking all ancestors on the left side before visiting the current person and then the right side relatives.
Example
This example shows how inorder traversal prints the values of a binary tree in sorted order.
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def inorder_traversal(root): if root is None: return [] return inorder_traversal(root.left) + [root.value] + inorder_traversal(root.right) # Create a simple binary search tree root = Node(4) root.left = Node(2) root.right = Node(6) root.left.left = Node(1) root.left.right = Node(3) root.right.left = Node(5) root.right.right = Node(7) # Perform inorder traversal result = inorder_traversal(root) print(result)
When to Use
Inorder traversal is especially useful when you want to retrieve data from a binary search tree in sorted order. For example, if you store numbers or words in a tree, inorder traversal will list them from smallest to largest.
It is also used in algorithms that need to process nodes in a specific order, such as expression trees where inorder traversal can recreate the original expression with operators and operands in the correct sequence.
Key Points
- Inorder traversal visits nodes in left-node-right order.
- It produces sorted output for binary search trees.
- It can be implemented using recursion or a stack.
- Useful for expression trees and sorted data retrieval.