Skip to content
CodeItRaw
Trees

Lesson 1/3

A binary tree is made of nodes; each node has a value and at most two children: left and right. The node at the top is the root, those without children are leaves. The point is this: a node's left and its right are each a tree in their own right. That is why tree questions suit recursion so well.

def total(node):
if node is None:
return 0
return node.val + total(node.left) + total(node.right)
The pattern hardly ever changes: what is the answer for an empty tree (the base case), and how does a node's answer come from the answers of its two children? For the sum: an empty tree is 0, and a node is its own value plus the sums of its two subtrees.

The order in which you visit the nodes has names. In-order: the left subtree first, then the node itself, then the right. Pre-order: node, left, right. Post-order: left, right, node. The only difference is where the line about the node stands relative to the two calls.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    In-order Walk

    Code reading · Predict the Output

  2. 02

    Tree Sum

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list