In-order Traversal of Binary Search Tree
In-order traversal is one of the fundamental tree traversal techniques. For a Binary Search Tree (BST), in-order traversal visits nodes in non-decreasing (ascending) order of their values. This makes it particularly useful for retrieving sorted data from a BST.
Traversal Order
In-order traversal follows the pattern: Left → Root → Right. For every node, you first visit its left subtree, then the node itself, and finally its right subtree.
Recursive Implementation
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorder_recursive(root, result=None):
if result is None:
result = []
if root:
inorder_recursive(root.left, result)
result.append(root.val)
inorder_recursive(root.right, result)
return result
# Example usage
root = Node(5)
root.left = Node(3)
root.right = Node(8)
root.left.left = Node(2)
root.left.right = Node(4)
print(inorder_recursive(root)) # Output: [2, 3, 4, 5, 8]
Iterative Implementation (Using Stack)
def inorder_iterative(root):
result = []
stack = []
current = root
while stack or current:
while current:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.val)
current = current.right
return result
# Output: [2, 3, 4, 5, 8]
Complexity
| Aspect | Complexity |
|---|---|
| Time | O(n) — visits every node exactly once |
| Space (recursive) | O(h) — recursion stack, h = height of tree |
| Space (iterative) | O(h) — explicit stack, worst-case O(n) for skewed tree |
Key Properties
- For a BST, in-order traversal produces a sorted list of all values.
- It is often used to validate whether a binary tree is a BST (check if the traversal output is sorted).
- It is a depth-first traversal (DFS) technique.
Applications
- Extracting sorted data from a BST without additional sorting cost.
- Validating BST properties (checking if in-order output is strictly increasing).
- Finding the k-th smallest element in a BST (by stopping early during traversal).
- Tree serialization and deserialization.
Following the Stack Step by Step
The iterative version is easier to trust once you watch the stack change. Using the example tree with root 5, left child 3 (children 2 and 4) and right child 8:
| Action | Stack (bottom to top) | Output so far |
|---|---|---|
| Push 5, 3, 2 while going left | 5, 3, 2 | empty |
| Pop 2, it has no right child | 5, 3 | 2 |
| Pop 3, move to right child 4 and push it | 5, 4 | 2, 3 |
| Pop 4 | 5 | 2, 3, 4 |
| Pop 5, move to right child 8 and push it | 8 | 2, 3, 4, 5 |
| Pop 8, stack and current are empty | empty | 2, 3, 4, 5, 8 |
The stack always holds the chain of ancestors whose left side is still being processed. That is why its size never exceeds the tree height.
Morris Traversal: In-order With No Extra Memory
Both versions above need O(h) extra space. Morris traversal brings this down to O(1) by temporarily linking each node's in-order predecessor back to it, then removing the link after use.
def inorder_morris(root):
result = []
current = root
while current:
if current.left is None:
result.append(current.val)
current = current.right
else:
pred = current.left
while pred.right and pred.right is not current:
pred = pred.right
if pred.right is None:
pred.right = current # create temporary thread
current = current.left
else:
pred.right = None # remove thread, restore tree
result.append(current.val)
current = current.right
return result
Time stays O(n), because each edge is walked a bounded number of times. The trade-off is that the tree is modified during traversal, so it is unsafe if other threads read the tree at the same time.
Validating a BST and Finding the k-th Smallest
Instead of storing the whole traversal and checking it afterwards, track only the previous value. The moment a value is not larger than the previous one, the tree is not a valid BST.
def is_valid_bst(root):
prev = None
stack, current = [], root
while stack or current:
while current:
stack.append(current)
current = current.left
current = stack.pop()
if prev is not None and current.val <= prev:
return False
prev = current.val
current = current.right
return True
For the k-th smallest element, use the same loop with a counter and return as soon as the counter reaches k. On a balanced tree with a small k, this touches only a small part of the tree.
Where Beginners Slip
- Checking only parent and child. A tree where every node is larger than its left child can still be invalid, because a deep node may break the rule against a grandparent. In-order checking catches this; local comparisons do not.
- Using a mutable default argument. Writing
result=[]directly in the function signature shares one list across calls in Python. TheNonecheck in the recursive version avoids that. - Deep recursion on skewed trees. A tree built from already sorted input can be as tall as it is large, which may exceed Python's recursion limit. Prefer the iterative form for unknown input.
- Mixing up traversal orders. Pre-order (Root, Left, Right) suits copying a tree; post-order (Left, Right, Root) suits deleting one; in-order is the one that yields sorted output.