Trees · Problem 1 of 3

How many levels does the org chart have?

Pattern: Maximum Depth of a Binary Tree

easyNot solved yet

The problem

A small company's org chart is a binary tree: each person has at most two direct reports. Write a function that returns how many levels the chart has, counting the root's level as 1. An empty chart has 0 levels.

A TreeNode class with val, left and right is provided. Trees are written as level-order arrays, with None (null in JavaScript) for a missing person.

text
1count_levels([1, 2, 3, None, 4])  ->  3
2count_levels([1])                 ->  1
3count_levels([])                  ->  0
Example 1
1level 12level 23level 24level 3

The deepest person, 4, is on level 3.

In the first example, 1 manages 2 and 3, and 2 manages 4, so there are three levels.

Write count_levels(root) in Python or countLevels(root) in JavaScript. Examples are written in Python: in JavaScript, None is null and True / False are true / false.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 16 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.