Simple level order with modification O(n) time complexity


#1

Logic: reverse order of queue push and then reverse the vector before returning

vector Solution::solve(TreeNode* A) {
if(A==NULL) return {};

queue<TreeNode*> q;
vector<int>res;

q.push(A);
while(q.size())
{
    TreeNode* temp=q.front();
    q.pop();
    
    if(temp!=NULL)
    {
        res.push_back(temp->val);
        if(temp->right) q.push(temp->right); // push in reverse order
        if(temp->left)  q.push(temp->left);
    }
}
reverse(res.begin(),res.end());
return res;

}