把二叉树打印多行_JAVA_中等
把二叉树打印成多行
http://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288
- 利用队列进行层次遍历,每次遍历时记录该层数量即可
import java.util.*; public class Solution { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> result = new ArrayList(); Queue<TreeNode> queue = new LinkedList(); if(pRoot != null) { queue.offer(pRoot); } while(!queue.isEmpty()) { // 输出一层 int n = queue.size(); ArrayList<Integer> list = new ArrayList(); while(n-- > 0) { TreeNode node = queue.poll(); list.add(node.val); // 存入孩子并计数 if(node.left != null) { queue.offer(node.left); } if(node.right != null) { queue.offer(node.right); } } result.add(list); } return result; } }