Skip to content
CodeItRaw
Trees

Lesson 2/3

Most tree questions are solved bottom-up: each node asks its children, combines the two answers it gets and hands its own answer up. For depth the combining is "take the larger and add one"; for the number of nodes it is "add the two and add one".

def depth(node):
if node is None:
return 0
return 1 + max(depth(node.left), depth(node.right))
The depth of an empty tree is 0, and of a one-node tree 1. The number you return in the base case shifts every answer: return 1 instead of 0 and every tree comes out one too deep.

Sometimes you ask a question about the node itself: is this a leaf? A leaf is a node whose children are both None. Counting leaves there are three cases: an empty tree (0), a leaf (1), an inner node (the two subtrees added; itself not counted).

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

    Tree Depth

    Code reading · Bug Hunt

  2. 02

    Depth

    Function

  3. 03

    Leaves

    Function

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