Tree Level with the Most Nodes
Problem statement
Given the root of a binary tree, return the zero-based depth that contains the greatest number of non-null nodes.
The root is at depth 0. If several depths contain the same maximum number of nodes, return the shallowest such depth. Return -1 for an empty tree.
Function
widestLevel(root: TreeNode) → intExamples
Example 1
root = [1,2,3,4,5,null,7]return = 2The level sizes are 1, 2, and 3, so depth 2 contains the most nodes.
Example 2
root = [1,2,3,4,null,null,5]return = 1Depths 1 and 2 each contain two nodes. The shallower tied depth is 1.
Example 3
root = []return = -1An empty tree has no level.
Constraints
- The tree contains at most
100000nodes. -100000 <= Node.val <= 100000.