Skip to the code
cf.
+10 XP

#325 Shallowest Leaf Pane

easy

In a split-pane layout, a pane with no children is a leaf: it shows real content. Keyboard users jump to the leaf that is fewest levels below the root.

Write shallowestLeaf(root) that returns the number of nodes on the shortest path from the root down to a leaf. A node with one child is not a leaf. An empty layout returns 0.

Example 1

Input: root = [1,2,3,null,null,4,5]
Output: 2

2 is a leaf on level 2, so the path 1 → 2 has two nodes.

Example 2

Input: root = [1,2]
Output: 2

The root has a child, so it is not a leaf. The only leaf is 2.

Constraints

  • 0 <= number of panes <= 100000

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).