剑指 Offer 32 - II. 从上到下打印二叉树 II
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { //结果集res List<List<Integer>> res = new ArrayList<>(); if(root == null){//判空 return res; } Queue<TreeNode> queue = new LinkedList();//存放TreeNode 队列 queue.add(root);//根节点入队 while(!queue.isEmpty()){//遍历队列queue ArrayList<Integer> ans = new ArrayList<>();//定义一个list,装同一层的TreeNode for(int i = queue.size();i > 0;i--){ TreeNode node = queue.poll(); ans.add(node.val); if(node.left != null){ queue.add(node.left); } if(node.right != null){ queue.add(node.right); } } res.add(ans); } return res; } }