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.
Explanation:
计算树的最小深度
My Thinking:
使用递归,每次返回两个子树深度的最小值即可。
My Solution:
class Solution {
public int minDepth(TreeNode root) {
if(root==null)
return 0;
int left=minDepth(root.left);
int right=minDepth(root.right);
if(left==0 || right==0)//注意当两个子树深度只有一个为0时要取非零的子树深度
return left+right+1;
else
return 1+Math.min(left,right);
}
}
Optimum Thinking:
Optimum Solution: