Shortest Downward Trip From the Root to a Leaf

Implement shortestLeafPath

You are given the root of a binary tree. Return the number of nodes on the shortest path that starts at the root and ends at a leaf. A leaf is a node with no children at all; a node that has only one child is not a leaf. For an empty tree, return 0.

The recursive solution must take care with nodes that have a single child. Searching level by level is often simpler, because the first leaf you meet is automatically on the shortest path.

Example 1:

Input: root = [12,7,20,3,9,null,30,1]

Output: 3

Example 2:

Input: root = [5,null,8]

Output: 2

Example 3:

Input: root = []

Output: 0

+ 12 hidden test cases run on Submit.

Constraints:

  • ●0 ≤ number of nodes ≤ 100
  • ●−100 ≤ node.val ≤ 100
  • ●The tree is given as its root node (null for an empty tree); each node has a val, a left child and a right child
  • ●A leaf is a node with no children at all. Return the number of nodes on the shortest path from the root down to any leaf (0 for an empty tree). A node with only one child is NOT a leaf

root =

[12, 7, 20, 3, 9, null, 30, 1]