Binary Trees Depth first: return a value up
355. Minimum Depth of Binary Tree
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
Input: root = [6, 2, 11, null, 9, 4, 13, null, null, 8]
3Explanation: 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
Input: root = [-3, -7, null, null, 0]
3Explanation: 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 = []
0Explanation: 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.
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.