oneby7

Binary Trees Breadth first: level by level

369. Maximum Width of Binary Tree

Medium

You are given root, the root node of a binary tree. Return the width of its widest level.

The root is the only node on the first level. Its children make up the second level, their children the third, and so on. Picture the tree drawn as if every node had both children: the first level has 1 position, the second 2, the third 4, and each level twice as many as the one above. A missing node leaves its position empty, and so do all the nodes that would have been below it.

The width of a level is the number of positions from its leftmost node to its rightmost node, counting both of them and every empty position between them. A level with one node has width 1.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

72419683

Input: root = [1, 4, 6, 2, null, 9, 8, 7, null, null, null, null, 3]

Output: 8

Explanation: The bottom level has 8 positions. 7 is in the first and 3 in the last, so its width is 8, though only two nodes are there. The level above holds 2, 9 and 8 across 4 positions.

Example 2

-7-8-5057

Input: root = [0, -5, 5, -7, null, null, 7, null, -8]

Output: 4

Explanation: On the third level, −7 and 7 sit at the two ends of its 4 positions, so its width is 4. The bottom level holds only −8, so its width is 1.

Example 3

-310⁹9

Input: root = [9, -3, null, null, 1000000000]

Output: 1

Explanation: Every level holds one node, so every level has width 1.

Check your understanding

Work out the answer for this input before you write any code.

root = [5, 1, 8, 4, null, null, 7, null, 2, 3]

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.
  • No level is wider than 231 − 1, so the answer fits in a 32-bit signed integer.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.