题解 | #把二叉树打印成多行#
把二叉树打印成多行
http://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
双队列实现,第一层打印完存第二层,第二层打印时存入第三层
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
TreeNode root = pRoot;
Queue<TreeNode> queue = new LinkedList<>();
Queue<TreeNode> queue2 = new LinkedList<>();
ArrayList<ArrayList<Integer> > list = new ArrayList<>();
TreeNode op;
queue.offer(root);
if(root == null){
return list;
}
while(true){
List<Integer> li = new ArrayList<>();
while(!queue.isEmpty()){
op = queue.poll();
if(op.left != null){
queue2.offer(op.left);
}
if(op.right != null){
queue2.offer(op.right);
}
li.add(op.val);
}
if(li.size() != 0){
list.add(new ArrayList(li));
}
li.clear();
while(!queue2.isEmpty()){
op = queue2.poll();
if(op.left != null){
queue.offer(op.left);
}
if(op.right != null){
queue.offer(op.right);
}
li.add(op.val);
}
if(li.size() != 0){
list.add(new ArrayList(li));
}
li.clear();
if(queue.isEmpty() && queue2.isEmpty()){
break;
}
}
return list;
}
}