Advanced graphs and trees · 1 / 15 Theory

How to traverse a binary tree

A binary tree can be traversed in four usual ways. The first three are recursive and differ only in when the node is visited with respect to its children; the fourth uses a queue.

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

#        1
#       / #      2   3
#     / #    4   5
tree = Node(1, Node(2, Node(4), Node(5)), Node(3))

def preorder(n):                      # node, left, right
    return [] if n is None else [n.value] + preorder(n.left) + preorder(n.right)

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

def postorder(n):                     # left, right, node
    return [] if n is None else postorder(n.left) + postorder(n.right) + [n.value]

print(preorder(tree))     # [1, 2, 4, 5, 3]
print(inorder(tree))      # [4, 2, 5, 1, 3]
print(postorder(tree))    # [4, 5, 2, 3, 1]

from collections import deque
def level_order(root):
    queue, levels = deque([root]), []
    while queue:
        levels.append([n.value for n in queue])
        for _ in range(len(queue)):
            n = queue.popleft()
            queue.extend(h for h in (n.left, n.right) if h)
    return levels

print(level_order(tree))  # [[1], [2, 3], [4, 5]]

def es_bst(n, low=float("-inf"), high=float("inf")):
    if n is None:
        return True
    return low < n.value < high and es_bst(n.left, low, n.value) and es_bst(n.right, n.value, high)

print(es_bst(Node(2, Node(1), Node(3))))             # True
print(es_bst(Node(5, Node(1), Node(6, Node(3)))))    # False (the 3 is on the right of the 5)
TraversalOrderTypical use
Preordernode, left, rightCopying a tree, serializing it
Inorderleft, node, rightIn a BST it gives the values sorted
Postorderleft, right, nodeDeleting a tree, evaluating expressions
Level orderlevel by level (queue)Distance to the root, “layered” views
  • To validate a BST it is not enough to compare each node with its children: you must pass down the allowed range (low, high).
  • The inorder of a valid BST is a strictly increasing list, another way to check it.
  • The lowest common ancestor is obtained with the path from the root to each node: the last node where both paths coincide.

You practice it in Binary tree traversals, Level-order traversal, Lowest common ancestor and Validate a search tree.