广度优先算法和深度优先算法类似是较为优雅的暴力算法,时间复杂度为o(n^2)
解题模板
- 定义Queue
- 加入初始条件
- 队列不为空的while循环
3.0 业务处理
3.1 for循环将队列元素逐一取出进行处理
3.2 将下一条件放入队列中
3.3 将符合条件的一种结果放入结果集中 - 返回结果集
接下来用LeetCode中的一些题目来验证如上解题模板
题目展示
1. 二叉树的层序遍历
根据要求编写代码
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
// 1. 定义队列
Queue<TreeNode> queue = new LinkedList<>();
// 2.加入初始条件
queue.offer(root);
// 3. 队列不为空的while循环
while(!queue.isEmpty()){
List<Integer> oneRes = new ArrayList<>();
int n = queue.size();
// 3.1 for循环将队列元素逐一取出进行处理
for(int i = 0;i < n;++i){
TreeNode temp = queue.poll();
// 3.0 业务处理
oneRes.add(temp.val);
// 3.2 将下一条件放入队列中
if(temp.left!=null){
queue.offer(temp.left);
}
if(temp.right!=null){
queue.offer(temp.right);
}
}
// 3.3 将符合条件的一种结果放入结果集中
res.add(oneRes);
}
// 4. 返回结果集
return res;
}
}
2. N叉树的层序遍历
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
// 1. 定义队列
Queue<Node> queue = new LinkedList<>();
// 2.加入初始条件
queue.offer(root);
// 3. 队列不为空的while循环
while(!queue.isEmpty()){
List<Integer> oneRes = new ArrayList<>();
int n = queue.size();
// 3.1 for循环将队列元素逐一取出进行处理
for( int i = 0; i < n; i++){
Node temp = queue.poll();
// 3.0 业务处理
oneRes.add(temp.val);
// 3.2 将下一条件放入队列中
List<Node> child = temp.children;
for(int j = 0;j < child.size(); j++){
if(child.get(j)!=null){
queue.offer(child.get(j));
}
}
}
// 3.3 将符合条件的一种结果放入结果集中
res.add(oneRes);
}
// 4. 返回结果集
return res;
}
}
3. 员工的重要性
class Solution {
public int getImportance(List<Employee> employees, int id) {
int res = 0;
Map<Integer,Employee> map = new HashMap<>();
for(int i = 0;i<employees.size();++i){
map.put(employees.get(i).id,employees.get(i));
}
// 1. 定义队列
Queue<Employee> queue = new LinkedList<>();
// 2.加入初始条件
queue.offer(map.get(id));
// 3. 队列不为空的while循环
while(!queue.isEmpty()){
Employee curr = queue.poll();
// 3.0 业务处理
res += curr.importance;
// 3.1 for循环将队列元素逐一取出进行处理
for(int i = 0;i<curr.subordinates.size();i++){
// 3.2 将下一条件放入队列中
queue.offer(map.get(curr.subordinates.get(i)));
}
}
// 4. 返回结果集
return res;
}
}