Solution using queue and level order traversal


#1

/**

  • Definition for binary tree
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    /
    vector Solution::solve(TreeNode
    A, int B) {
    queue<TreeNode*>q;int flag=0;vectorv;
    q.push(A);q.push(NULL);
    while(q.front()!=NULL and flag!=3){
    TreeNode* temp=q.front();
    q.pop();
    if(flag==2){
    v.push_back(temp->val);
    }
    int x=0;int y=0;
    if(temp->left){x=temp->left->val;}
    if(temp->right){y=temp->right->val;}
    if(x==B or y==B){
    flag++;
    }
    else{
    if(temp->left)q.push(temp->left);
    if(temp->right)q.push(temp->right);
    }
    if(q.front()==NULL and flag>0){flag++;}
    if(q.front()==NULL){
    q.pop();
    q.push(NULL);
    }
    }
    return v;
    }