Introduction
Imagine you have a collection of numbers stored in a special tree, and you want to see them in order from smallest to largest. The problem is how to visit each number so that you get this sorted list without rearranging the tree.
Imagine a library where books are arranged so that all books with earlier publication years are on the left shelves and later years on the right. Walking through the library by first checking the left shelves, then the current shelf, and finally the right shelves lets you see books from oldest to newest.
┌─────┐
│ 10 │
└──┬──┘
│
┌──────┴──────┐
│ │
┌──┴──┐ ┌──┴──┐
│ 5 │ │ 15 │
└──┬──┘ └──┬──┘
│ │
┌──┴──┐ ┌──┴──┐
│ 3 │ │ 20 │
└─────┘ └─────┘
Inorder traversal visits nodes in this order: 3 → 5 → 10 → 15 → 20class Node: def __init__(self, val): self.val = val self.left = None self.right = None def inorder_traversal(root): if root is None: return [] return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right) # Create BST root = Node(10) root.left = Node(5) root.right = Node(15) root.left.left = Node(3) root.right.right = Node(20) # Get sorted values sorted_values = inorder_traversal(root) print(sorted_values)