FunctionRacerProblemsRace

Maximum Width of Binary Tree

MediumTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. The width of a level is the distance from its leftmost to its rightmost existing node, counting the empty positions between them as if the tree were a full tree (so a level whose only nodes are at the far left and far right is wide). Number the positions on each level from 0: the children of position p are 2p and 2p+1 on the next level. A level's width is rightmost - leftmost + 1. Return the largest width of any level. An empty tree gives 0.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [1,3,2,5,null,null,9,6,null,7]
returns 7

The last level has nodes at positions 0 and 6 (the 6 and the 7), so its width is 7.

Example 2

root [1,2,3,4]
returns 2

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

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems