题解 | #把二叉树打印成多行#
把二叉树打印成多行
http://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
二叉树的层序打印
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); Deque<TreeNode> queue = new ArrayDeque<>(); if(pRoot != null) queue.addLast(pRoot); while (!queue.isEmpty()){ ArrayList<Integer> list = new ArrayList<>(); //i一定要先从queue.size开始,因为队列里 的元素随时在变,必须先复制确定下来 'for (int i = queue.size(); i > 0; i--) {' TreeNode node = queue.removeFirst(); list.add(node.val); if (node.left != null) queue.addLast(node.left); if (node.right != null) queue.addLast(node.right); } result.add(list); } return result; }