Binary Tree

Maximum Depth Visualizer

What is Maximum Depth

The depth of the tree is the number of nodes on the longest path from the root to a leaf. A single node has depth 1. An empty child has depth 0.

1 2 3 4
depth 3

Approach

Ask each child for its depth, then add one for the current node. The larger child decides the answer.

Empty childA missing child returns 0. That is why a leaf, whose children are both missing, has depth 1.
Take the larger sideThe node's depth is 1 plus the deeper child. The root's answer is the depth of the whole tree.

The picture labels each finished node with the depth it returns. The highlighted node is the one being computed.

Interactive solution

Depth returned from the leaves upward
def depth(node):
if node is null: return 0
left = depth(node.left)
right = depth(node.right)
return 1 + max(left, right)
Step 0/0 Answer —

The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each node is visited once.
Call stackO(h)A spine of n nodes uses n calls.

Implementation

def depth(node):
    if not node:
        return 0
    return 1 + max(depth(node.left), depth(node.right))