C++|BFS|Easy|using 2 queues


#1

/**

  • Definition for binary tree
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    /
    #define vi vector
    #define vvi vector
    #define pb push_back
    vector<vector > Solution::levelOrder(TreeNode
    node) {
    vvi ans;
    if(node==NULL)return ans;
    queue <TreeNode* > q1,q2;
    q1.push(node);
    while(!q1.empty()||!q2.empty())
    {
    vi temp;
    if(q1.empty())
    {
    while(!q2.empty())
    {
    TreeNode* root=q2.front();
    q2.pop();
    temp.pb(root->val);
    if(root->left)q1.push(root->left);
    if(root->right)q1.push(root->right);
    }
    }
    else if(q2.empty())
    {
    while(!q1.empty())
    {
    TreeNode* root=q1.front();
    q1.pop();
    temp.pb(root->val);
    if(root->left)q2.push(root->left);
    if(root->right)q2.push(root->right);
    }
    }
    if(!temp.empty())ans.pb(temp);
    }
    return ans;
    }