BFS算法解题框架
核心数据结构:队列
Queue<T> q=new LinkedList<T>();
常用框架:
public int bfs(起始点){
int res=0;//返回值,根据返回类型定义
Queue<T> q=new LinkedList<T>();
q.offer(起始点);
while(!q.isEmpty()){
int sz=q.size();
for(int i=0;i<sz;i++){
T t=q.poll();
if(到达终点) return res;
//给q添加t的相邻点
q.offer(t的相邻点且没有被使用过的点)
}
//更新步数在for循环体外面
depth++;
}
return depth;
}
力扣111 二叉树的最小深度
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
Queue<TreeNode> q=new LinkedList();
q.offer(root);
int depth=1;
while(!q.isEmpty()){
int sz=q.size();
for(int i=0;i<sz;i++){
TreeNode node=q.poll();
if(node.left==null&&node.right==null) return depth;
if(node.left!=null) q.offer(node.left);
if(node.right!=null) q.offer(node.right);
}
depth++;
}
return depth;
}
}
力扣102 二叉树的层序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list=new LinkedList<>();
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
while(!q.isEmpty()){
List<Integer> level=new LinkedList<>();
int size=q.size();
for(int i=0;i<size;i++){
TreeNode cur=q.poll();
if(cur==null) continue;
level.add(cur.val);
q.offer(cur.left);
q.offer(cur.right);
}
if (!level.isEmpty()) {
list.add(level);
}
}
return list;
}
}