LeetCode中BFS总结

       广度优先搜索的搜索过程有像一层一层地进行遍历,每层遍历都以上一层遍历的结果作为起点,遍历一个长度。

实现 BFS 时需要考虑以下问题:

  • 队列:用来存储每一轮遍历的节点;

  • 标记:对于遍历过的节点,应该将它标记,防止重复遍历。

  • 只能用来求解无权图的最短路径问题。

典型例题就是:计算在网格中从原点到特定点的最短路径长度

leetcode102. Binary Tree Level Order Traversal  数的层次遍历,还有leetcode103也是类似的。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    //广度优先遍历
    public List> levelOrder(TreeNode root) {
        List> list = new LinkedList<>();
    	Queue queue = new LinkedList<>();
    	if (root==null)	return list;
    	
    	queue.offer(root);
    	while (!queue.isEmpty()) {
    		List subList = new LinkedList<>();
    		int level = queue.size();
    		for (int i=0; i

 

 

你可能感兴趣的:(数据结构,LeetCode)