Intermediate 16 min

Recursion and tree traversal

Visit tree branches with smaller calls and identify what stops each branch.

Use a smaller input in each call

A binary tree node can have a left and right child. Count nodes by adding one for the current node and counting each child subtree. An absent child is the base case and contributes zero. Every recursive call gets a strict subtree when the input is a finite acyclic tree.

How it works

For a tree traversal, decide what the function does for one node, then let the same function handle its children. A missing child is an immediate return. For a nonempty tree, the order in which you visit the current node and its subtrees changes the output.

Distinguish work from call depth

The traversal takes O(n) time because each node is processed once. The maximum number of active calls is proportional to height. A balanced binary tree has logarithmic height, while a chain of n nodes has linear height and may exceed a runtime’s call stack.

Code example

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

def count_nodes(node):
    if node is None:
        return 0
    return 1 + count_nodes(node.left) + count_nodes(node.right)

print(count_nodes(Node(Node(), Node(Node()))))

Check your understanding

Count all nodes in each tree. A missing child contributes zero.

See the example and explanation
Example 1
Given Root R has children A and B. B has child C.
Answer 4
Example 2
Given No root node
Answer 0

A leaf returns one because both of its children are missing. A root with a two-node subtree and a one-node subtree returns 1 + 2 + 1, or four.

Open practice problem
Next lessonBreadth-first search