Problem 422354 · easy · Phase 04 Non-Linear Data Structures

Maximum Depth of Binary Tree

binary tree · recursion · DFS

A binary tree's depth (or height) is the number of nodes on the longest path from the root down to a leaf. It is the simplest tree recursion: the depth of a tree is one more than the depth of its taller subtree.

Given the root of a binary tree, return its maximum depth. An empty tree has depth 0.

Examples

    3
   / \
  9  20
    /  \
   15   7

Input:  root = [3, 9, 20, None, None, 15, 7]
Output: 3
  1
   \
    2
     \
      3

Input:  root = [1, None, 2, None, 3]
Output: 3
Input:  root = []
Output: 0

Trees are given in level-order list form: the list is read top to bottom, left to right, with None marking a missing child.

Constraints

  • 0 <= number of nodes <= 1000

Goals

  • Navigate a TreeNode structure via .left and .right
  • Use None as the base case of a tree recursion
  • Combine answers from the two subtrees into an answer for the whole tree
Starting Python…