classSolution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = newLinkedList();
if (root != null) { recursiveLevelOrder(0, ans, root); }
return ans; } // an int variable 'level' is needed to record which level a node is privatevoidrecursiveLevelOrder(int level, List<List<Integer>> ans, TreeNode node) { if (node == null) { return; }
// if the list which would record this node has not been created, new one and record if (ans.size() <= level) { List<Integer> list = newLinkedList<>(); list.add(node.val); ans.add(list); }else{ ans.get(level).add(node.val); }
// actually, no need to check if left or right is null if (node.left != null) { recursiveLevelOrder(level + 1 , ans, node.left); }
if (node.right != null) { recursiveLevelOrder(level + 1, ans, node.right); }