Code

Walking the Tree

A binary tree is made of nodes where each node has up to two children: left and right. The top node is the root; nodes with no children are leaves.

        B
      /   \
     A     D
          / \
         C   E

Trees are recursive: every child is the root of a smaller tree. So tree code is usually recursive too, with None as the base case.

Three ways to walk

  • Preorder: node, then left, then right gives B A D C E
  • Inorder: left, then node, then right gives A B C D E
  • Postorder: left, then right, then node gives A C E D B
def count(node):
    if node is None:
        return 0
    return 1 + count(node.left) + count(node.right)

Height

The height is the number of nodes on the longest path from the root down to a leaf. An empty tree has height 0, a single node 1.

Assignment

  1. preorder(node) returns a list of values in preorder.
  2. inorder(node) returns a list of values in inorder.
  3. height(node) returns the tree's height (None has height 0).