Levels in the Org Chart

Easy · Trees & BSTs · about 10 min

A company's org chart is a binary tree: every person has at most two direct reports. The tree is a level-order list: the root first, then each node's left and right child in turn, with None (Python) / null (JavaScript) for a missing child. A build(level) helper in the starter turns it into nodes with .val, .left and .right.

Return the number of levels in the chart: the number of people on the longest chain from the top person down to someone with no reports, counting both ends. An empty chart has 0 levels.

  • Up to 10,000 people. Values are employee ids (any integers, repeats allowed).

Examples:

chart_levels([1, 2, 3, 4, None, None, 5, 6]) → 4 (the chain 1 → 2 → 4 → 6)

chart_levels([]) → 0

Hints

  • What is the answer for an empty chart? That is your base case.
  • For any person, how do the levels below them relate to the levels below each of their two reports?
  • Take one plus the larger of the two answers, never just one side.

Learn the pattern first: the Trees & BSTs lesson.

More Trees & BSTs problems