Problem
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
1 |
|
return its minimum depth = 2.
Explanation
- First, we check if the root node is empty, if it is empty, then return 0.
- If the root node doesn’t have left and right child, then return 1.
- If the root node only has right child, then we return 1 plus the min length of the right subtree.
- If the root node only has left child, then we return 1 plus the min length of the left subtree.
- If the root node has both left and right child, then we return 1 plus the minimum of min length left subtree and min length of the right subtree.
Solution
1 |
|