This problem has bug in output


#1

Don’t waste your time like I did, trying to find out how every row of my solution array has only one column.

public class Solution {
private ArrayList<ArrayList> list;
public int[][] levelOrder(TreeNode n) {
list = new ArrayList<ArrayList>();

    traverse(n, 0);
    int[][] sol = new int[list.size()][];
    for (int i=0; i<list.size(); i++) {
        ArrayList<Integer> row = list.get(i);
        sol[i] = new int[row.size()];
        
        for (int j=0; j<row.size(); j++) {
            sol[i][j] = row.get(j);
        }
    }
    return sol;
}

private void traverse(TreeNode n, int l) {
    if (n == null)
        return;
    if (list.size() == l)
        list.add(new ArrayList<Integer>());
    if (list.get(l) == null)
        list.set(l, new ArrayList<Integer>());
    list.get(l).add(n.val);
    traverse(n.left, l + 1);
    traverse(n.right, l + 1);
}

}