Adding unnecessary vectors at last, Please solve the error in the code


#1
vector<vector<int> > ans;
int t=-1;
void formlevels(TreeNode* A, int h){
    if(A==NULL)return;
    if(t<h){
        vector<int> temp;
        ans.push_back(temp);
    }
    formlevels(A->left,h+1);
    ans[h].push_back(A->val);
    formlevels(A->right,h+1);
}
vector<vector<int> > Solution::levelOrder(TreeNode* A) {
    ans.resize(0);
    t=-1;
    formlevels(A,0);
    return ans;
}

#2

The problem is that you are not updating variable t. because of that it will push a empty vector for each node.
hint: Add the following line somewhere in your code

t = (int)ans.size()-1;