剑指60.把二叉树打印成多行
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路
见 二叉树层序遍历问题总结
解法
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<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer> > ans = new ArrayList<>(); if (pRoot == null) return ans; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(pRoot); while (!queue.isEmpty()){ int levelNums = queue.size(); ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < levelNums; i++) { TreeNode cur = queue.poll(); list.add(cur.val); if (cur.left != null) queue.offer(cur.left); if (cur.right != null) queue.offer(cur.right); } ans.add(list); } return ans; } }