Data Structures & Algorithms · Module 8 · Lesson 11 min read

Binary Trees & Traversals

Vocabulary

  • Node: holds a value and links to its children.
  • Root: the top node. Leaf: a node with no children.
  • Binary tree: each node has at most 2 children (left and right).
  • Height: the longest path from the root to a leaf.

Traversals (ways to visit every node)

OrderVisitUse
Pre-ordernode → left → rightcopying or serialising a tree
In-orderleft → node → rightsorted output from a BST
Post-orderleft → right → nodedeleting, computing sizes
Level-order (BFS)row by row, with a queueshortest depth, printing levels

All are O(n).

The recursive mindset

Most tree problems look like this:

Python
def solve(node):
    if node is None:
        return BASE
    left = solve(node.left)
    right = solve(node.right)
    return combine(node.val, left, right)

Examples: height, size, sum, maximum, "is it balanced?", "are two trees equal?".

Space

Recursion uses O(h) stack space, where h is the height: O(log n) for a balanced tree, O(n) for a tree that looks like a line.

Example

Python
from collections import deque

class Node:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

#        1
#      /   \
#     2     3
#    / \     \
#   4   5     6
root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))

def preorder(n):  return [] if not n else [n.val] + preorder(n.left) + preorder(n.right)
def inorder(n):   return [] if not n else inorder(n.left) + [n.val] + inorder(n.right)
def postorder(n): return [] if not n else postorder(n.left) + postorder(n.right) + [n.val]

def height(n):
    return 0 if not n else 1 + max(height(n.left), height(n.right))

def level_order(root):
    levels, q = [], deque([root])
    while q:
        levels.append([n.val for n in q])
        q = deque(c for n in q for c in (n.left, n.right) if c)
    return levels

print(preorder(root))     # [1, 2, 4, 5, 3, 6]
print(inorder(root))      # [4, 2, 5, 1, 3, 6]
print(postorder(root))    # [4, 5, 2, 6, 3, 1]
print(height(root))       # 3
print(level_order(root))  # [[1], [2, 3], [4, 5, 6]]