oneby7

Binary Trees Depth first: return a value up

355. Minimum Depth of Binary Tree

Easy

You are given root, the root node of a binary tree. Return the minimum depth of the tree.

The minimum depth is the number of nodes on the shortest path that starts at the root and goes down to a leaf. A leaf is a node with no children. A node with only one child is not a leaf, so a path cannot end there. An empty tree has minimum depth 0.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

296841113

Input: root = [6, 2, 11, null, 9, 4, 13, null, null, 8]

Output: 3

Explanation: The leaves are 9, 13 and 8. The shortest paths to a leaf, 6 → 2 → 9 and 6 → 11 → 13, have 3 nodes each. Node 2 has no left child, but it is not a leaf, so a path cannot end there.

Example 2

-70-3

Input: root = [-3, -7, null, null, 0]

Output: 3

Explanation: The root has only a left child, −7, and −7 has only a right child, 0. The only leaf is 0, so the shortest path is the whole tree.

Example 3

Input: root = []

Output: 0

Explanation: The tree has no nodes, so its minimum depth is 0.

Check your understanding

Work out the answer for this input before you write any code.

root = [4, null, 7, 1, 3]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.