EZ c++ sol using 2 queue


#1
vector<int> Solution::solve(TreeNode* A) {
    queue<TreeNode*> s,t;
    vector<int> v,vv;
    s.push(A);
    while(!s.empty())
    {
        TreeNode* temp = s.front();
        s.pop();
        v.push_back(temp->val);
        
        if(temp->left) t.push(temp->left);
        if(temp->right) t.push(temp->right);
        
        if(s.empty())
        {
            s.swap(t);
            vv.swap(v);
            for(int i=0;i<v.size();i++)
            {
                vv.push_back(v[i]);
            }
            v.clear();
        }
    }
    return vv;
}

#2

It can be done only by using one queue
vector Solution::solve(TreeNode* A)
{
vector ans;
ans.clear();
if(A==NULL)
return ans;
queue<TreeNode*> q;
q.push(A);
while(!q.empty())
{
int n = q.size();
while(n–)
{
TreeNode* temp = q.front();
q.pop();
ans.push_back(temp->val);
if(temp->right)
q.push(temp->right);
if(temp->left)
q.push(temp->left);
}
}
reverse(ans.begin(),ans.end());
return ans;
}


#3

/**

  • Definition for binary tree
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    */
    #include<bits/stdc++.h>
    using namespace std;
    #define fastio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);

typedef long long ll;
typedef long double ld;
typedef double db;

typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
typedef pair<db,db> pd;

typedef vector vi;
typedef vector vl;
typedef vector vd;
typedef vector vpi;
typedef vector vpl;
typedef vector vpd;

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)(x).size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pf push_front
#define pb push_back
#define em empty
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#include
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353
const int MOD2=998244353;
const int N = 2e5+5;
const int INF = INT_MAX;
vector Solution::solve(TreeNode* A) {
vi ans;
queue<TreeNode*>q;
q.push(A);
while(!q.empty()){
int d=sz(q);
while(d–){
ans.pb(q.front()->val);
if(q.front()->right!=nullptr) q.push(q.front()->right);
if(q.front()->left!=nullptr) q.push(q.front()->left);
q.pop();
}
}
reverse(all(ans));
return ans;
}