Why My code show error?


#1

Plz Give 2-3 min
vector Solution::solve(TreeNode* A, int B) {
vector v;
queue<TreeNode *> q;
q.push(A);
if(A->val==B)
return {};
while(q.size()!=0)
{
int size=q.size();
for(int i=0;i<size;i++)
{
TreeNode *curr=q.front();
q.pop();
if((curr->left && curr->left->val==B) || (curr->right && curr->right->val==B))
{
int si=q.size();
for(int j=0;j<si;j++)
{
TreeNode *cu=q.front();
q.pop();
if(cu->left)
v.push_back(cu->left->val);
if(cu->right)
v.push_back(cu->right->val);
}
return v;
}
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
}
}
return v;
}


#2

The logic of putting the for loop (of si) inside the while is wrong. Put it outside. By your logic when you see that one of the children is B you are putting everything in the queue into vector v. But there will be the parent’s cousins also inside the queue at that stage (You need only the child’s cousins).