CodeArchon

easyTreesGoogleMetaAmazon

Canopy Height Scanner

An aerial LiDAR inspects tree canopies as nested branch nodes to calculate the maximum canopy depth.

Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Choose approach

3
curr
9
20
15
7
1/11
Narrationstep 1 of 11

Visit node 3. Recurse left and right to determine heights.

1def maxDepth(root: Optional[TreeNode]) -> int:
2 if not root:
3 return 0
4 return 1 + max(maxDepth(root.left), maxDepth(root.right))
Variables
curr=3

How to think about it

  1. Height of a null node is 0.
  2. Height of any valid node is one plus the max height of its left and right children.
  3. Solve bottom-up to minimize stack depth.

Edge cases to catch in interview

  • Empty tree -> depth = 0.
  • Straight line tree (linked list equivalent) -> height = n.

Examples

Example 13
{"arr":[3,9,20,null,null,15,7]}
Example 22
{"arr":[1,null,2]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed