Easy C++ solution( BFS approach )


#1
vector<int> Solution::solve(TreeNode* A, int B) 
{
    if(A->val==B)
    {
        return {};
    }
    vector<int>v;
    queue<TreeNode *>q;
    q.push(A);
    bool found=false;
    while(!q.empty())
    {
        int n=q.size();
        vector<int>tmp;
        while(n)
        {
            TreeNode *node=q.front();
            q.pop();
            if((node->left && node->left->val==B) || (node->right && node->right->val==B))
            {
                found=true;
            }
            else
            {
                if(node->left)
                {
                    tmp.push_back(node->left->val);
                    q.push(node->left);
                }
                if(node->right)
                {
                    tmp.push_back(node->right->val);
                    q.push(node->right);
                }
            }
            n--;
        }
        if(found)
        {
            v=tmp;
            break;
        }
    }
    return v;
}