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.
解题思路:
递归求解,如果有比min还小的深度,就更新min,需要注意的是,最小深度是叶子节点到根节点的深度。如果左子树或右子树为空,那么这个就不能计算在内。
public class Solution {
int min;
public int minDepth(TreeNode root) {
min = Integer.MAX_VALUE;
DepthOfTree(root,0);
return min;
}
public void DepthOfTree(TreeNode root,int depth){
if(root == null){
if(min > depth)
min = depth;
return ;
}
if(root.left == null)
DepthOfTree(root.right,depth+1);
else if(root.right == null)
DepthOfTree(root.left,depth+1);
else{
DepthOfTree(root.left,depth+1);
DepthOfTree(root.right,depth+1);
}
}
}
本文介绍了一种通过递归方法解决二叉树最小深度问题的算法。最小深度定义为从根节点到最近叶子节点的最短路径长度。文章详细解释了算法实现步骤,并通过代码实例展示了如何应用此算法。

519

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



