class Solution { List<List<Integer>> res = new ArrayList<>(); public List<List<Integer>> levelOrder(TreeNode root) { dfs(root,1); return res; } public void dfs(TreeNode root, int level) { if(root == null) return; if(res.size() < level) res.add(new ArrayList<>()); res.get(level-1).add(root.val); dfs(root.left,level+1); dfs(root.right,level+1); } }