原题
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;
}
}

本文介绍了一种求解二叉树最小深度的算法。该算法递归地遍历二叉树,找到从根节点到最近叶子节点的最短路径长度。通过检查左右子节点的存在情况来确定递归路径。
424

被折叠的 条评论
为什么被折叠?



