Solution With map


#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*>q;
    map<int,vector>v;
    map<TreeNode*,int>mp;
    if(A==NULL)
    return ans;
    q.push(A);
    mp[A]=0;
    while(!q.empty())
    {
    TreeNode *x=q.front();
    q.pop();
    v[mp[x]].push_back(x->val);

     if(x->left!=NULL)
     {q.push(x->left);mp[x->left]=1+mp[x];}
     if(x->right!=NULL)
     {q.push(x->right);mp[x->right]=1+mp[x];}
    

    }
    int n=v.size();
    ans.resize(n);
    for(auto it:v)
    {
    int z=it.first;
    for(int i=0;i<v[z].size();i++)
    ans[z].push_back(v[z][i]);
    }
    return ans;
    }