题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:
对比从上到下打印二叉树https://blog.youkuaiyun.com/orangefly0214/article/details/83743664
以及上一个题目:按之字形顺序打印二叉树https://blog.youkuaiyun.com/orangefly0214/article/details/87907869
不管是广度优先遍历有向图还是一棵树,都需要用到队列。首先将根节点放入队列,接下来每次从队列头部取出一个节点,遍历这个节点之后把它能到达的子节点都依次放入队列。重复这个过程,直到队列中的所有节点全部被遍历为止。
实现1:
和二叉树的深度的广度优先遍历一样,用队列存储,每层打印之前,记录size得到该层节点数,完成每一层的打印。
public class Solution {
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ret=new ArrayList<ArrayList<Integer>>();
if(pRoot==null) return ret;
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.offer(pRoot);
while(!queue.isEmpty()){
ArrayList<Integer> sub=new ArrayList<Integer>();
int size=queue.size();
for(int i=0;i<size;i++){
TreeNode node=queue.poll();
sub.add(node.val);
if(node.left!=null){
queue.offer(node.left);
}
if(node.right!=null){
queue.offer(node.right);
}
}
if(!sub.isEmpty()){
ret.add(sub);
}
}
return ret;
}
}
实现2:
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ret=new ArrayList<ArrayList<Integer>>();
if(pRoot==null){
return null;
}
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.add(pRoot);
int toBePrinted=1;
int nextLine=0;
ArrayList<Integer> sublist=new ArrayList<>();
while(!queue.isEmpty()){
TreeNode curr=queue.poll();
sublist.add(curr.val);
--toBePrinted;
if(curr.left!=null){
queue.add(curr.left);
++nextLine;
}
if(curr.right!=null){
queue.add(curr.right);
++nextLine;
}
if(toBePrinted==0){
ret.add(sublist);
sublist=new ArrayList<>();
toBePrinted=nextLine;
nextLine=0;
}
}
return ret;
}
}