问题:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/*
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<>();
Queue<TreeNode> q=new LinkedList<>();
if(pRoot==null)
return ret;
q.add(pRoot);
int lastCount=1;
while(!q.isEmpty())
{
int count=0;
ArrayList<Integer> tmp=new ArrayList<>();
for(int i=0;i<lastCount;i++)
{
TreeNode tmp_node=q.poll();
tmp.add(tmp_node.val);
if(tmp_node.left!=null)
{
q.add(tmp_node.left);
count++;
}
if(tmp_node.right!=null)
{
q.add(tmp_node.right);
count++;
}
}
ret.add(tmp);
lastCount=count;
}
return ret;
}
}