BFS
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
if(root == null) return list;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
ArrayList<Integer> child = new ArrayList<>();
while(size -- != 0){
TreeNode node = queue.poll();
child.add(node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
list.add(child);
}
return list;
}
DFS
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int h = 0;
helper(list,h,root);
return list;
}
private void helper(ArrayList<ArrayList<Integer>> list,int h,TreeNode root){
if(root == null) return ;
if(h >= list.size()){
list.add(new ArrayList<>());
}
list.get(h).add(root.val);
helper(list,h+1,root.left);
helper(list,h+1,root.right);
}