Can anyone explain, why this is showing runtime error?


#1

vector<vector > Solution::levelOrder(TreeNode* A) {
queue<TreeNode*> q;
queue<TreeNode*> nq;
vector<vector> ans;
if(A!=NULL)
q.push(A);
int i=0;
while(!q.empty()){
ans.push_back({});
while(!q.empty()){
TreeNode* temp=q.front();
q.pop();
ans[i].push_back(temp->val);
if(temp->left)
nq.push(temp->left);
if(temp->right);
nq.push(temp->right);
}
q=nq;
while(!nq.empty())
nq.pop();
i++;
}
return ans;
}


#2

You are pushing null values into the queue. Supposed temp->left or temp->right are null you are still pushing them. When they are popped ie temp=NULL you get seg. Simple solution is add if statements before push statements