【剑指offer刷题总结】树的广度优先遍历(BFS)
-
广度优先遍历-
广度优先遍历,又称BFS,是指按照层的顺序来访问节点,当一层的所有节点被访问完之后再进行下一层的访问。
一般使用一个辅助队列来实现,这是因为队列是先入先出的数据结构:- 根节点入队列
- 取出队列头节点,同时加入该节点的左子节点和右子节点(如果存在的话),这样保证了从左到右的遍历顺序。
- 重复2,直到队列为空
基本的代码如下:
public void bfs(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode temp = queue.poll();
System.out.println(temp.val);
if(temp.left!=null) queue.add(temp.left);
if(temp.right!=null) queue.add(temp.right);
}
}
整理一下上面的代码,让方法返回一个int数组,就是剑指offer的32题:
public int[] levelOrder(TreeNode root){
//注意空值判断
if(root == null) return new int[0];
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> list = new ArrayList<>();
queue.add(root);
int count = 0;
while (!queue.isEmpty()){
TreeNode temp = queue.poll();
list.add(temp.val); count++;
if(temp.left!=null) queue.add(temp.left);
if(temp.right!=null) queue.add(temp.right);
}
int[] res = new int[count];
for (int i = 0; i < count; i++) {
res[i] = list.get(i);
}
return res;
}
如果要求改一下,变成同一层节点从左到右打印,且每层单独打印一行,即返回一个二维数组形式,就是剑指offer32题的变形:
public static List<List<Integer>> levelOrder(TreeNode root){
//借助辅助队列实现,从左到右遍历
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int n = queue.size();
List<Integer> temp = new ArrayList<>();
//遍历n次,确保遍历完此层的每个结点(按照之前入队顺序出队)
//同时把下一层的节点加入队列中
for (int i = 0; i < n; i++) {
TreeNode node = queue.poll();//出队列
temp.add(node.val);
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
res.add(temp);
}
return res;
}
要求继续升级,要求按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
public List<List<Integer>> levelOrder(TreeNode root){
//关键点:辅助数组使用linked list,双端队列,可以从后向前加元素
List<List<Integer>> res = new ArrayList<>();
int count = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
int n = queue.size();
LinkedList<Integer> tempList = new LinkedList<>();
count++;
for (int i = 0; i < n; i++) {
TreeNode temp = queue.poll();
if(count%2 == 0) tempList.addLast(temp.val);
else tempList.addFirst(temp.val);
if(temp.left!=null) queue.add(temp.left);
if(temp.right!=null) queue.add(temp.right);
}
res.add(tempList);
}
return res;
}