JAVA solution in O(N) using queue


#1
public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode A) {
        //ER_DEEPAK_KR
        ArrayList<ArrayList<Integer>>list=new ArrayList<>();
        if(A==null) return list;
        Queue<TreeNode>q=new LinkedList<>();
        q.add(A);
        q.add(new TreeNode(Integer.MIN_VALUE));
        ArrayList<Integer>temp=new ArrayList<>();
        while(!q.isEmpty())
        {
            TreeNode x=q.remove();
            temp.add(x.val);
            
            if(x.left!=null) q.add(x.left);
            if(x.right!=null) q.add(x.right);
            if(!q.isEmpty()&&q.peek().val==Integer.MIN_VALUE)
            {
                list.add(new ArrayList<>(temp));
                temp=new ArrayList<>();
                q.remove();
                q.add(new TreeNode(Integer.MIN_VALUE));
                
            }
            
        }
        return list;
    }
}