BFS——广度优先算法(Breadth First Search)-CSDN博客
1.N叉树的层序遍历(广度优先搜索)
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> ret=new LinkedList<>();
if(root==null){
return ret;
}
Queue<Node> q=new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
int sz=q.size();
List<Integer> tmp = new ArrayList<>(); // 统计本层的结点信息
for(int i=0;i<sz;i++){
Node t=q.poll();
tmp.add(t.val);
//让孩子入队
for(Node child:t.children){
if(child!=null){
q.add(child);
}
}
}
ret.add(tmp);
}
return ret;
}
}
2.⼆叉树的锯⻮形层序遍历
103. 二叉树的锯齿形层序遍历 - 力扣(LeetCode)
增加一个标记位,让偶数行存储信息的数据逆序
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ret = new LinkedList<List<Integer>>();
if (root == null) {
return ret;
}
Queue<TreeNode> q=new LinkedList<>();
q.add(root);
int level=1;
while(!q.isEmpty()){
int sz=q.size();
List<Integer> list=new LinkedList<>();
for(int i=0;i<sz;i++){
TreeNode t=q.poll();
list.add(t.val);
if(t.left!=null){
q.add(t.left);
}
if(t.right!=null){
q.add(t.right);
}
}
//判断是否逆序
if(level%2==0){
Collections.reverse(list);
}
level++;
ret.add(list);
}
return ret;
}
}
3.二叉树最大宽度
class Solution {
public int widthOfBinaryTree(TreeNode root) {
List<Pair<TreeNode, Integer>> q = new ArrayList<>(); // ⽤数组模拟队列
q.add(new Pair<TreeNode, Integer>(root, 1));
int ret = 0; // 记录最终结果
while (!q.isEmpty()) {
// 先更新⼀下这⼀层的宽度
Pair<TreeNode, Integer> t1 = q.get(0);
Pair<TreeNode, Integer> t2 = q.get(q.size() - 1);
ret = Math.max(ret, t2.getValue() - t1.getValue() + 1);
// 让下⼀层进队
List<Pair<TreeNode, Integer>> tmp = new ArrayList<>();
for (Pair<TreeNode, Integer> t : q) {
TreeNode node = t.getKey();
int index = t.getValue();
if (node.left != null) {
tmp.add(new Pair<TreeNode, Integer>(node.left, index * 2));
}
if (node.right != null) {
tmp.add(new Pair<TreeNode, Integer>(node.right, index * 2
+ 1));
}
}
q = tmp;
}
return ret;
}
}
4.在每个树行中找最大值
515. 在每个树行中找最大值 - 力扣(LeetCode)
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> ret = new ArrayList<>();
if (root == null)
return ret;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int sz = q.size();
int tmp = Integer.MIN_VALUE;
for (int i = 0; i < sz; i++) {
TreeNode t = q.poll();
tmp = Math.max(tmp, t.val);
if (t.left != null)
q.add(t.left);
if (t.right != null)
q.add(t.right);
}
ret.add(tmp);
}
return ret;
}
}
标签:12,队列,List,ret,BFS,int,add,new,root
From: https://blog.csdn.net/m0_47017197/article/details/140078448