Skip to content

Binary trees and traversal

A binary tree node has a value and at most two child references. A child can itself be the root of a smaller tree. The empty tree is None, which gives recursive algorithms a natural base case.

The tree in this lesson stores integer search keys. Its root is 8, its left child is 3, and its right child is 11. Node 3 has children 1 and 6. The example is invented for this lesson.

Return the values in left subtree, root, right subtree order. This is an inorder traversal. Also return the maximum depth, measured in nodes from the root to a leaf. The empty tree has depth zero.

A valid input is a finite tree without cycles or shared child nodes. The algorithms below do not check that contract. A reference cycle would prevent recursive traversal from terminating.

class TreeNode:
"""Store one integer and its optional child references.
Attributes:
value: Integer stored at this node.
left: Root of the left subtree, or None.
right: Root of the right subtree, or None.
"""
def __init__(
self,
value: int,
left: "TreeNode | None" = None,
right: "TreeNode | None" = None,
) -> None:
"""Initialize a node.
Args:
value: Integer stored at this node.
left: Optional left child.
right: Optional right child.
"""
self.value = value
self.left = left
self.right = right
def append_inorder(node: TreeNode | None, result: list[int]) -> None:
"""Append a subtree's values in inorder.
Args:
node: Root of a finite binary tree, or None.
result: Destination list to extend.
"""
if node is None:
return
append_inorder(node.left, result)
result.append(node.value)
append_inorder(node.right, result)
def inorder_recursive(root: TreeNode | None) -> list[int]:
"""Return an inorder traversal using recursive calls.
Args:
root: Root of a finite binary tree, or None.
Returns:
Values in left subtree, root, right subtree order.
"""
result: list[int] = []
append_inorder(root, result)
return result
def maximum_depth(root: TreeNode | None) -> int:
"""Return the greatest root-to-leaf node count.
Args:
root: Root of a finite binary tree, or None.
Returns:
The maximum depth, with zero for the empty tree.
"""
if root is None:
return 0
return 1 + max(maximum_depth(root.left), maximum_depth(root.right))
tree = TreeNode(8, TreeNode(3, TreeNode(1), TreeNode(6)), TreeNode(11))
print("Recursive inorder:", inorder_recursive(tree))
print("Maximum depth:", maximum_depth(tree))
Recursive inorder: [1, 3, 6, 8, 11]
Maximum depth: 3

The recursive contract is local. If each child call appends its subtree in the required order, the parent places its own value between the two child results. The empty subtree appends nothing. This proves the traversal by induction on the number of nodes.

The helper appends to one shared result list. Concatenating complete left and right lists at every return would repeatedly copy values on a tall tree.

Replace recursive calls with an explicit stack

Section titled “Replace recursive calls with an explicit stack”

The stack holds ancestors whose values remain to be emitted. Follow left children until no child remains. Pop the nearest ancestor, emit it, and then enter its right subtree. A popped node’s left subtree is already complete.

def inorder_iterative(root: TreeNode | None) -> list[int]:
"""Return an inorder traversal using an explicit stack.
Args:
root: Root of a finite binary tree, or None.
Returns:
Values in left subtree, root, right subtree order.
"""
result: list[int] = []
stack: list[TreeNode] = []
current = root
while current is not None or stack:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.value)
current = current.right
return result
stack: list[TreeNode] = []
current = tree
while current is not None or stack:
while current is not None:
stack.append(current)
print("Push", current.value, "stack", [node.value for node in stack])
current = current.left
current = stack.pop()
print("Visit", current.value, "stack", [node.value for node in stack])
current = current.right
print("Iterative inorder:", inorder_iterative(tree))
Push 8 stack [8]
Push 3 stack [8, 3]
Push 1 stack [8, 3, 1]
Visit 1 stack [8, 3]
Visit 3 stack [8]
Push 6 stack [8, 6]
Visit 6 stack [8]
Visit 8 stack []
Push 11 stack [11]
Visit 11 stack []
Iterative inorder: [1, 3, 6, 8, 11]

Let n be the node count and h the maximum depth. Each traversal visits every node once and costs O(n) time. Its auxiliary stack occupies O(h) space, while the returned list occupies another O(n) space. The depth function also costs O(n) time and O(h) auxiliary space.

These bounds describe inorder_recursive, inorder_iterative, and maximum_depth. The demonstration also copies the stack for each printed state. Those copies can add O(n * h) work, which becomes quadratic for a chain.

A balanced tree has logarithmic height. A chain has height n. Python limits recursive call depth, so a long chain can raise RecursionError; an explicit stack avoids that call-depth limit.

Distinguish a binary tree from a search tree

Section titled “Distinguish a binary tree from a search tree”

For a binary search tree with distinct keys, every key in a node’s left subtree is smaller than that node. Every key in its right subtree is larger. The rule applies to whole subtrees, not only the immediate children.

Inorder traversal produces increasing values only when this ordering rule holds. Ordinary binary trees need not be ordered. Duplicate keys require an explicit policy before insertion or validation can be correct.

Searching a binary search tree follows one child at each step and costs O(h) time. That is O(log n) for a balanced tree and O(n) for a chain. Calling every tree search logarithmic ignores its shape.

assert inorder_recursive(None) == []
assert inorder_iterative(None) == []
assert maximum_depth(None) == 0
single = TreeNode(5)
assert inorder_iterative(single) == [5]
assert maximum_depth(single) == 1
chain = TreeNode(2, None, TreeNode(4, None, TreeNode(9)))
assert inorder_recursive(chain) == inorder_iterative(chain)
assert maximum_depth(chain) == 3
unordered = TreeNode(2, TreeNode(7), TreeNode(1))
assert inorder_iterative(unordered) == [7, 2, 1]
print("The empty, singleton, chain, and unordered cases pass.")
The empty, singleton, chain, and unordered cases pass.

Maximum Depth of Binary Tree tests whether your base case and depth convention agree. Compare a balanced example with a chain before you state the space cost.

Validate Binary Search Tree requires bounds inherited from ancestors. Construct a node that satisfies its parent’s rule but violates its grandparent’s rule.

Download the Python source to run the complete example locally.

MIT’s binary search tree material explains the search ordering rule. Use it to separate the properties of a binary tree from the additional properties of a search tree.

Python’s recursion limit documentation describes the interpreter’s call-depth limit. It explains why a correct recursive algorithm can still fail on a deep input.