给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
方法1:递归
方法一:深度优先搜索
思路及解法
首先可以想到使用深度优先搜索的方法,遍历整棵树,记录最小深度。
对于每一个非叶子节点,我们只需要分别计算其左右子树的最小叶子节点深度。这样就将一个大问题转化为了小问题,可以递归地解决该问题。
实现代码:
public int minDepth(TreeNode root) {
if(root == null)
return 0;
if (root.left == null && root.right == null) {
return 1;
}
int minDepth = Integer.MAX_VALUE;
if(root.left != null){
minDepth = Math.min(minDepth,minDepth(root.left));
}
if(root.right != null){
minDepth = Math.min(minDepth,minDepth(root.right));
}
return minDepth + 1;
}
方法2:迭代
方法二:广度优先搜索(BFS Breadth--first-search)
思路及解法
同样,我们可以想到使用广度优先搜索的方法,遍历整棵树。
当我们找到一个叶子节点时,直接返回这个叶子节点的深度。广度优先搜索的性质保证了最先搜索到的叶子节点的深度一定最小。
public int minDepth(TreeNode root) {
if(root == null)
return 0;
Queue<TreeNode> q = new LinkedList<>();
int depth = 1;
q.offer(root);
while(!q.isEmpty()){
int size = q.size();
for(int i = 0; i < size;i++){
TreeNode cur = q.poll();
if(cur.left == null && cur.right == null){
return depth;
}
if(cur.left != null){
q.offer(cur.left);
}
if(cur.right != null){
q.offer(cur.right);
}
}
depth += 1;
}
return depth;
}
这篇博客介绍了如何计算二叉树的最小深度,提供了两种解法:递归和广度优先搜索(BFS)。递归方法通过分别计算非叶子节点的左右子树深度来找到最小深度;而BFS方法则利用队列进行层次遍历,一旦找到叶子节点即返回其深度。这两种方法都是有效的解决方案。
425

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



