一、BFS算法
- BFS问题的本质就是,在“一幅图”中找到从起点到终点的最近距离。比如两个单词,将一个替换字幕后变成另一个单词,需要的最小替换次数。
- 问题的框架:
int BFS(Node start, Node target) {
Queue<Node> q;
Set<Node> visited;//避免走回头路
q.offer(start);//入队
visited.add(start);
int step = 0;//记录步数
while(q not empty){
int sz = q.size();//记住,一定要先取出q的大小,这样才能保证每次将当前q中的周边节点全部入队
for(int i=0; i<sz; i++){
Node cur = q.poll();//出队
if(cur is target) {
return step;
}
//将周边节点都入队
for(Node x : cur.adj()){
if(x not in visited){
q.offer(x);
visited.add(x);
}
}
}
step++;
}
}
- 当BFS应用于树时,周边节点指的便是树的子节点。一定要注意先取出q的大小后,才能进行for循环遍历取出当前队列中所有的节点,并将队列中所有节点的子节点入队,否则因为队列中的节点随时都在添加,会造成队列大小变化
二、二叉树的最小高度
- 问题描述:给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。(力扣链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/)
- 代码如下:
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int depth = 1;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()){
int queueSize = queue.size();
//向四周扩散
for (int i = 0; i < queueSize; i++) {//遍历一层
TreeNode cur = queue.poll();
if(cur.left==null && cur.right==null){
return depth;
}
//cur的相邻节点(下一层)加入队列
if(cur.left!=null){
queue.offer(cur.left);
}
if(cur.right!=null){
queue.offer(cur.right);
}
}
depth++;
}
return depth;
}