Easy understandable C++ solution using bfs


#1

/**

  • Definition for binary tree
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    /
    vector<vector > Solution::levelOrder(TreeNode
    A) {
    vector<vector>ans;
    queue<TreeNode*>qe;
    vectorq;
    qe.push(A);
    TreeNode n=new TreeNode(-1);
    qe.push(n);
    bool prevn=false;
    while(!qe.empty())
    {
    TreeNode
    p=qe.front();
    qe.pop();
    if(p->val==-1)
    {
    if(!q.empty())
    ans.push_back(q);
    qe.push(n);
    q.clear();
    if(prevn)
    break;
    else
    prevn=true;
    continue;
    }
    else if(prevn)
    prevn=false;
    q.push_back(p->val);
    if(p->left)
    qe.push(p->left);
    if(p->right)
    qe.push(p->right);
    }
    return ans;
    }