Simple O(N) C++ solution using two queue and BFS


#1
queue<TreeNode*>q;
vector<vector<int> >ans;
vector<int>t;
t.push_back(A->val);
ans.push_back(t);
q.push(A);
while(!q.empty())
{
    queue<TreeNode*>tq;
    while(!q.empty())
    {
        TreeNode* A=q.front();
        q.pop();
        if(A->left!=NULL)
            tq.push(A->left);
        if(A->right!=NULL)
            tq.push(A->right);
    }
    vector<int>temp;
    while(!tq.empty())
    {
        TreeNode* A=tq.front();
        temp.push_back(A->val);
        q.push(A);
        tq.pop();
    }
    if(temp.size()>0)
        ans.push_back(temp);
}
return ans;