Short and easy c++ solution with explanation


#1
    vector<vector<int>> ans;
    if(A==NULL){
        return ans;
    }
    queue<TreeNode*>q;
    q.push(A);
    while(!q.empty()){
        int n=q.size();      //number of values in the level
        vector<int> currentlevel;
        for(int i=0;i<n;i++){
            TreeNode *current= q.front();
            q.pop();
            currentlevel.push_back(current->val);
            if(current->left!=NULL){   //if left child exist
                q.push(current->left);
            }
            if(current->right!=NULL){    //if right child exist
                q.push(current->right);
            }
        }
        ans.push_back(currentlevel);
    }
    return ans;
}