题目:给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
输出最小深度2
题解:这道题如果用DFS算法,则需要遍历完整棵树才能得出结果,如果使用BFS算法,则遇到的第一个叶子结点的深度就是结果。
BFS代码
class Solution {
//class nodeDepth用于保存每个结点的深度,是整个BFS算法的关键
class nodeDepth{
TreeNode node;
int depth;
public nodeDepth(TreeNode node, int depth) {
this.node = node;
this.depth = depth;
}
}
public int minDepth(TreeNode root) {
if(root==null)
return 0;
Queue<nodeDepth> BFS=new LinkedList<>();
BFS.offer(new nodeDepth(root,1));
while(!BFS.isEmpty()){
nodeDepth peek=BFS.poll();
if(peek.node.left==null&&peek.node.right==null)
return peek.depth;
if(peek.node.left!=null)
BFS.offer(new nodeDepth(peek.node.left, peek.depth+1));
if(peek.node.right!=null)
BFS.offer(new nodeDepth(peek.node.right, peek.depth+1));
}
return -1;
}
}