| 17 | |
| 18 | class Solution { |
| 19 | public List<List<Integer>> levelOrder(TreeNode root) { |
| 20 | List<List<Integer>> ans=new LinkedList<List<Integer>>() ; |
| 21 | if(root==null) return ans ; |
| 22 | Queue<TreeNode> q=new LinkedList() ; |
| 23 | q.add(root) ; |
| 24 | while(q.size()>0){ |
| 25 | int cs=q.size() ; |
| 26 | List<Integer> temp=new LinkedList<>() ; |
| 27 | // to add all the nodes present on the same level |
| 28 | while(cs-->0){ |
| 29 | TreeNode cn=q.remove() ; |
| 30 | temp.add(cn.val) ; |
| 31 | if(cn.left!=null) q.add(cn.left) ; |
| 32 | if(cn.right!=null) q.add(cn.right) ; |
| 33 | } |
| 34 | ans.add(temp) ; |
| 35 | } |
| 36 | return ans ; |
| 37 | } |
| 38 | } |