Problem 262
Maximum Width of Binary Tree
Medium · 20 pts · Tree, Binary Tree, Breadth-First Search
Problem
The width of one level of a binary tree is the number of positions from its leftmost node to its rightmost node, inclusive. Missing nodes between them still count, as if the level were part of a complete binary tree. Print the largest width over all levels. Number the positions like a heap: if a node has position p, its children have positions 2p and 2p + 1. The width of a level is then last position - first position + 1. Positions grow very fast in deep trees, so subtract the first position of each level to keep the numbers small.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child.
Output
Print the maximum width.
Constraints
1 <= number of nodes <= 3000; -100 <= value <= 100; the answer fits in a 64-bit integer
Example input
7 1 3 2 5 3 null 9
Example output
4
Explanation
The bottom level holds 5 and 3 under node 3, nothing under the first slot of node 2, and 9 as node 2's right child. From 5 to 9 the level spans 4 positions, including the missing one, so the maximum width is 4.