Ctrl K

Nearest Leaf Depth

Easy
You are given the root root of a binary tree. A leaf is a node with no children. Find the shortest path from the root down to any leaf and return the number of nodes on it, counting both the root and the leaf. If the tree is empty, return 0.
Example 1
root=tree_node([6, 2, 8, None, None, 7, 9]) → 2

Node 2 is a leaf right under the root, and the path 6 → 2 has two nodes.

Example 2
root=tree_node([1, None, 4, 3]) → 3

The root has no left child but is not a leaf itself; the only leaf is 3, reached by 1 → 4 → 3.

Example 3
root=tree_node([]) → 0

An empty tree has no nodes, so the answer is 0.

Constraints
  • The tree has between 0 and 10⁵ nodes
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIdentical Trees EasyMirror-Image Tree EasyTree Height EasyLeaf Path With a Given Total EasyMirror the Tree Easy
loading Python…
Input
root=tree_node([6, 2, 8, None, None, 7, 9])
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 98 tests on the server, hidden ones included.