剑指offer(把二叉树打印成多行)

题目分析
【剑指offer(把二叉树打印成多行)】从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
代码

import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }} */ public class Solution { ArrayList> Print(TreeNode pRoot) { ArrayList> res = new ArrayList<>(); if(pRoot == null) { return res; } Queue q = new LinkedList<>(); ArrayList layer = new ArrayList<>(); q.add(pRoot); int start = 0; int end = 1; // 记录每层的节点数 while(!q.isEmpty()) { TreeNode temp = q.remove(); layer.add(temp.val); start ++; if(temp.left != null) { q.add(temp.left); } if(temp.right != null) { q.add(temp.right); } if(start == end) { res.add(layer); end = q.size(); start = 0; layer = new ArrayList(); } } return res; }}

    推荐阅读