最近疯狂做了几篇BFS的文章
总结一下,BFS广度优先, 顾名思义,思路就是先探索遍所有的可能性,然后保存到queue,然后从queue里一个一个poll出来继续探索。
先探索广度!
常用的数据结构
queue是常见的implementation方式。queue.offer(), queue.poll()是一些method
Example
常见的题型就是level order traversal. 例如No. 104
"Given the root
of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node."
Input: root = [3,9,20,null,null,15,7] Output: 3
做法大概就是构建一个queue,然后queue.offer(root)
接着只要queue不empty,就把queue的一个node poll()出来,把它的children(也就是node.left, node,right) 都加进来,再继续接着探索。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
int count = 0;
if(root == null) return count;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int i = queue.size();
while(i > 0){
TreeNode cur = queue.poll();
if(cur.left != null) queue.add(cur.left);
if(cur.right != null) queue.add(cur.right);
i--;
}
count = count + 1;
}
return count;
}
}
这就是非常典型的一类BFS的应用题型,探索遍且囊括当下所有的可能性,再进行下一步。
类似的题目还有No.101, No. 102, No. 111