Elegant and short java solution using BFS


#1

public class Solution {
public ArrayList<ArrayList> levelOrder(TreeNode A) {
ArrayList<ArrayList> ans = new ArrayList<>();
LinkedList lst = new LinkedList<>();
lst.addFirst(A);
while(!lst.isEmpty()){
int n = lst.size();
ArrayList lvl = new ArrayList<>();
for(int i = 0;i<n;i++){
TreeNode tmp = lst.pollFirst();
lvl.add(tmp.val);
if(tmp.left!=null){
lst.addLast(tmp.left);
}
if(tmp.right!=null){
lst.addLast(tmp.right);
}
}
ans.add(lvl);
}
return ans;
}
}