Skip to the code
cf.
+25 XP

#328 Widest Row Including Gaps

medium

A tree diagram is drawn on a grid where every level has room for a full set of slots: level d has 2^d slots, and each node's children take the two slots below it. Empty slots between nodes still take space.

Write widestRow(root) that returns the largest width of any level, where a level's width is the number of slots from its leftmost node to its rightmost node, counting both and every slot between them. An empty tree returns 0.

Example 1

Input: root = [1,2,3,4,null,null,5]
Output: 4

On level 2, 4 is in slot 0 and 5 in slot 3, so the width is 4.

Example 2

Input: root = [1,2,3,4]
Output: 2

Level 1 has width 2. Level 2 has only 4, width 1.

Constraints

  • 0 <= number of nodes <= 3000
  • The answer fits in a 32-bit integer.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).