题目:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行
分析:和23题从上往下打印二叉树类似,用一个队列保存将要打印的结点,为了把二叉树的每一行单独打印到一行里,需要两个变量,即,一个变量表示当前层中还没有打印的结点数,一个变量表示下一层结点的数目
代码:按照剑指offer上思路直接输出,牛客上利用ArrayList来存储
import java.util.*;
public class wr60Print {
public static void printByHang(TreeNode root){
ArrayList<Integer> list=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
if(root==null){
return ;
}
queue.add(root);
int next=0;//表示下一层的结点数
int toBePrint=1;//当前行还没有打印的结点数
while(!queue.isEmpty()){
TreeNode temp=queue.peek();
System.out.print(temp.val+" ");
if(temp.left!=null){
queue.add(temp.left);
next++;
}
if(temp.right!=null){
queue.add(temp.right);
next++;
}
queue.poll();
toBePrint--;
if(toBePrint==0){
System.out.println();
toBePrint=next;
next=0;
}
}
}
public static ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > listall=new ArrayList<>();
ArrayList<Integer> list=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
if(pRoot==null){
return listall;
}
int next=0;
int toBe=1;
queue.add(pRoot);
while(!queue.isEmpty()){
TreeNode temp=queue.peek();
list.add(temp.val);
if(temp.left!=null){
queue.add(temp.left);
next++;
}
if(temp.right!=null){
queue.add(temp.right);
next++;
}
queue.poll();
toBe--;
if(toBe==0){
toBe=next;
next=0;
listall.add(list);
list=new ArrayList<Integer>();
}
}
return listall;
}
public static void main(String []args){
TreeNode root=new TreeNode(1);
root.left=new TreeNode(2);
root.right=new TreeNode(3);
root.left.left=new TreeNode(4);
root.left.right=new TreeNode(5);
root.right.left=new TreeNode(6);
root.right.right=new TreeNode(7);
printByHang(root);
ArrayList<ArrayList<Integer> > listall=Print(root);
for(int i=0;i<listall.size();i++){
System.out.println(listall.get(i));
}
}
}
输出结果
1
2 3
4 5 6 7
[1]
[2, 3]
[4, 5, 6, 7]