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

Levels in an Org Chart

binary tree · recursion · DFS

Tree recursion starts here. The depth of a binary tree counts the nodes on its longest root-to-leaf path, and it obeys a one-line rule: a tree is one level deeper than the deeper of its two subtrees.

A small studio draws its org chart as a binary tree, because nobody manages more than two people. Write max_depth(root) that returns how many levels the chart has: the number of people on the longest chain of command from the person at the top down to someone with no reports. An empty chart (None) has 0 levels.

Examples

      7
     / \
    2   9
   /     \
  1      12
   \
    3

Input:  root = [7, 2, 9, 1, None, None, 12, None, 3]
Output: 4
Explanation: the chain 7 -> 2 -> 1 -> 3 has four people.
  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…