TExcelTAD
Home › Data Structures & Algorithms › In-order Traversal

In-order Traversal

In an in-order traversal you visit a node in between its two subtrees:

  1. Traverse the left subtree in in-order.
  2. Visit the node itself.
  3. Traverse the right subtree in in-order.

We use the same tree as in the previous lesson:

text
            40
         /      \
       22        61
      /  \      /  \
    15    30   52   70
         /
       27

The visited values come out sorted. That is no coincidence, as we'll see below.

Recursive implementation

python · try it yourself
class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

root = Node(40,
            Node(22, Node(15), Node(30, Node(27))),
            Node(61, Node(52), Node(70)))

def inorder(node, out):
    if node is None:
        return
    inorder(node.left, out)      # 1. everything smaller
    out.append(node.value)       # 2. the node
    inorder(node.right, out)     # 3. everything larger

order = []
inorder(root, order)
print(order)
[15, 22, 27, 30, 40, 52, 61, 70]

Why the result is sorted

This tree is a binary search tree: for every node, all values in its left subtree are smaller and all values in its right subtree are larger. In-order visits "everything smaller, then the node, then everything larger" at every level, so the values come out in ascending order. This is a handy way to check whether a binary tree is a valid BST:

python · try it yourself
class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

def inorder(node):
    if node is None:
        return []
    return inorder(node.left) + [node.value] + inorder(node.right)

def is_bst(root):
    values = inorder(root)
    return all(a < b for a, b in zip(values, values[1:]))

good = Node(40, Node(22, Node(15), Node(30, Node(27))), Node(61, Node(52), Node(70)))
bad = Node(40, Node(22, Node(15), Node(45)), Node(61))   # 45 is in 40's left subtree
print(inorder(good), is_bst(good))
print(inorder(bad), is_bst(bad))
[15, 22, 27, 30, 40, 52, 61, 70] True
[15, 22, 45, 40, 61] False

Note: Checking only that each node's direct children are on the correct side is a common mistake. In the bad tree, 45 is a correct right child of 22, but it is in the left subtree of 40, so the tree is not a BST.

Iterative version

The iterative in-order traversal is a classic: go left as far as possible pushing nodes on a stack, then pop one, visit it, and continue with its right subtree.

python · try it yourself
class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

root = Node(40, Node(22, Node(15), Node(30, Node(27))), Node(61, Node(52), Node(70)))

def inorder_iterative(root):
    out, stack, node = [], [], root
    while stack or node:
        while node:                 # slide down to the leftmost node
            stack.append(node)
            node = node.left
        node = stack.pop()
        out.append(node.value)
        node = node.right
    return out

print(inorder_iterative(root))
[15, 22, 27, 30, 40, 52, 61, 70]

The k-th smallest value

Because in-order visits values in sorted order, you can stop early: the k-th visited node is the k-th smallest value. A generator makes stopping easy:

python · try it yourself
class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

root = Node(40, Node(22, Node(15), Node(30, Node(27))), Node(61, Node(52), Node(70)))

def inorder(node):
    if node:
        yield from inorder(node.left)
        yield node.value
        yield from inorder(node.right)

def kth_smallest(root, k):
    for i, value in enumerate(inorder(root), start=1):
        if i == k:
            return value

print([kth_smallest(root, k) for k in (1, 3, 5)])
[15, 27, 40]

In-order and expressions

For an expression tree, in-order gives the familiar infix notation. Parentheses must be added around each operator's subtree, since the tree's shape, not precedence, decides the order:

python · try it yourself
class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

expr = Node("*", Node("+", Node(3), Node(4)), Node("-", Node(10), Node(6)))

def infix(node):
    if node.left is None:                 # a number
        return str(node.value)
    return f"({infix(node.left)} {node.value} {infix(node.right)})"

print(infix(expr))
((3 + 4) * (10 - 6))

Test yourself

What does an in-order traversal of a binary search tree produce?

  1. The values in insertion order
  2. The values in ascending order
  3. The root first
  4. The leaves only

What is the in-order traversal of root 1 with left child 2 and right child 3, where 2 has a left child 4?

  1. 1 2 4 3
  2. 4 2 1 3
  3. 4 2 3 1
  4. 2 4 1 3

Why can't you verify a BST by checking only each node's two direct children?

  1. Children are always correct
  2. A value deep in a subtree can violate an ancestor's ordering
  3. It takes O(n²) time
  4. Leaves have no children