BFS算法又叫宽度优先搜索算法,引用百度的专业解释为
BFS属于一种盲目搜寻法,目的是系统地展开并检查图中的所有节点,以找寻结果。换句话说,它并不考虑结果的可能位置,彻底地搜索整张图,直到找到结果为止。
说实话我对算法这一块不懂,现在只是稍有理解并照葫芦画瓢,我想这算法更多的是为了方便某一类解决问题。
leetcode我遇到的使用bfs算法的有“走迷宫最优解”、“N-ary树的最大深度”这两道题目,现在先拿树的最大深度做自我讲解。
第一种解法,利用递归调用
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
private int max = 0;
private int cur = 1;
public int maxDepth(Node root) {
if(root == null){
return 0;
}
for(Node node : root.children){
cur++;
maxDepth(node);
}
if(cur > max){
max = cur;
}
cur--;
return max;
}
}
使用递归方法时,当遍历到最后一个节点返回时,将当前节点值赋予最大值,然后节点一级一级向上返回时,当前节点值-1,返回以及遍历其他节点时,拿当前节点值cur再与max进行比较。这种方法比较容易懂,但是不适合深度递归。
第二种则是使用BFS算法
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
if(root == null) return 0;
Queue<Node> queue = new LinkedList<>();
//将节点加入到队列中
queue.offer(root);
int depth = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
//弹出该队列头部元素
Node current = queue.poll();
for(Node child : current.children){
queue.offer(child);
}
}
depth ++;
}
return depth;
}
}
捋一下思路,如图所示:
2019-02-21
今天又做了一道类似的题,想了想,用了bfs算法,清晰明了。
首先看题目
A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
Example 1:
Input: [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: [2,2,2,5,2]
Output: false
大致意思就是说这个树种所有节点的值一样就返回true,不一样就返回false
上代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isUnivalTree(TreeNode root) {
//利用到了set集合去重的作用
Set set = new HashSet();
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
TreeNode current = queue.poll();
set.add(current.val);
if(current.left !=null ){
queue.offer(current.left);
}
if(current.right != null){
queue.offer(current.right);
}
}
}
if(set.size() == 1){
return true;
}
return false;
}
}
步骤上和第一题基本上是相似的