/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
LinkedList<TreeNode> childQueue = new LinkedList<TreeNode>();
queue.add(root);
int depth = 1;
while (!queue.isEmpty()){
TreeNode node = queue.remove();
if(node.left==null && node.right==null){
return depth;
}
if(node.left!=null){
childQueue.add(node.left);
}
if(node.right!=null){
childQueue.add(node.right);
}
if(queue.isEmpty() && !childQueue.isEmpty()){
depth++;
queue.addAll(childQueue);
childQueue.clear();
}
}
return depth;
}
}
本文介绍了一种使用广度优先搜索算法来确定二叉树最小深度的方法。通过实现一个名为minDepth的函数,该函数接收一个二叉树的根节点作为参数,并返回该树的最小深度。文章详细解释了如何利用队列来逐层遍历二叉树,一旦找到第一个叶子节点即可返回当前深度。
1354

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



