Typorithm · easy

Maximum Depth

max-depth-binary-treetreesrecursiondfsheight
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Maximum Depth

0%

Trees

Depth equals one plus the maximum depth of the two subtrees, with empty subtrees counting as zero.

The depth of a tree is the longest path from the root down to a leaf.

Each node adds one to the deeper of its two subtrees.

The base case — an empty subtree — has depth zero, anchoring the recursion.

01

Empty subtree depth is 0.

02

Take the max of both children.

03

Add 1 for the current node.

function maxDepth(root) {
  if (root === null) {
    return 0;
  }

  return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Empty is zero

A missing subtree contributes no depth.

if (root === null) {
    return 0;
  }

2. Deeper child

Depth is driven by the taller subtree.

Math.max(maxDepth(root.left), maxDepth(root.right))

3. Count this node

Add one for the current node above its children.

1 + Math.max

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Maximum Depth: Lesson & Practice · Typorithm | ApplyDjinn