Binary Trees Breadth first: level by level
369. Maximum Width of Binary Tree
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
Input: root = [1, 4, 6, 2, null, 9, 8, 7, null, null, null, null, 3]
8Explanation: 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
Input: root = [0, -5, 5, -7, null, null, 7, null, -8]
4Explanation: 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
Input: root = [9, -3, null, null, 1000000000]
1Explanation: 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.
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.