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.
Tags:Tree Depth-first Search
- 对仅有左/右子树的情况取该子树递归计算深度
- 对有左右子树或无子树情况直接递归计算深度
public class Solution {
public int minDepth(TreeNode root) {
if(root==null)return 0;
else if(root.left == null && root.right != null) return 1+minDepth(root.right);
else if(root.left != null && root.right == null) return 1+minDepth(root.left);
else{
int i = minDepth(root.left);
int j = minDepth(root.right);
return 1+(i>=j?j:i);
}
}
}