import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /* * 队列:Queue<TreeNode> queue=new LinkedList<>(); * 入队:offer * 出队:poll * 得到队头:peek * 大小:size * 空:isEmpty */ public class Solution { public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> res=new ArrayList<>(); if(root==null) return res; //层序遍历需要用到队列 Queue<TreeNode> queue=new LinkedList<>(); //推荐用offer代替add queue.offer(root); while(!queue.isEmpty()) { //用size控制循环次数 int size=queue.size(); ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<size;i++) { TreeNode node=queue.poll(); list.add(node.val); if(node.left!=null) queue.offer(node.left); if(node.right!=null) queue.offer(node.right); } res.add(list); } return res; } }