/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res=new ArrayList<List<Integer>>(); if(root==null) return res; Queue<TreeNode> q=new LinkedList<TreeNode>(); q.offer(root); int size=q.size(); int count=0; List<Integer> templist=new ArrayList<Integer>(); while(!q.isEmpty()) { TreeNode temp=q.poll(); if(temp.left!=null) q.offer(temp.left); if(temp.right!=null) q.offer(temp.right); count++; templist.add(temp.val); if(count==size) { size=q.size(); count=0; res.add(templist); templist=new ArrayList<Integer>(); } } return res; } }