把二叉树打印成多行
import java.util.ArrayList;
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>> m= new ArrayList<ArrayList<Integer>>();
if(pRoot==null)
return m;
LinkedList<TreeNode> deque=new LinkedList<TreeNode>();
deque.offer(pRoot);
int nextLevel = 0;
int toBePrinted = 1;
ArrayList<Integer> temp=new ArrayList<Integer>();
while(!deque.isEmpty()){
TreeNode pNode = deque.peek();
temp.add(pNode.val);
if(pNode.left!=null)
{
deque.offer(pNode.left);
nextLevel++;
}
if(pNode.right!=null)
{
deque.offer(pNode.right);
nextLevel++;
}
deque.poll();
toBePrinted--;
if(toBePrinted == 0)
{
toBePrinted=nextLevel;
nextLevel=0;
m.add((ArrayList<Integer>)temp.clone());
temp.clear();
}
}
return m;
}
}