原题
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.
题目分析
求最小深度。注意是从根到叶子的最小距离
代码实现
public class Solution {
public int MinDepth(TreeNode root) {
if(root==null)
return 0;
if(isLeaf(root))
return 1;
if(root.left==null)
return 1 + MinDepth(root.right);
if(root.right ==null)
return 1 + MinDepth(root.left);
return Math.Min(MinDepth(root.left),MinDepth(root.right))+1;
}
private bool isLeaf(TreeNode node)
{
return node.left==null && node.right==null;
}
}