Simple Solution using map in C++


#1

`/**

  • Definition for binary tree
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    /
    void findLevels(TreeNode
    A, map<int,vector>& mp, int pos){
    if(A==NULL){
    return;
    }
    mp[pos].push_back(A->val);
    findLevels(A->left,mp,pos+1);
    findLevels(A->right,mp,pos+1);
    }

vector<vector > Solution::zigzagLevelOrder(TreeNode* A) {
// if(A==NULL){
// return {};
// }
map<int,vector> mp;
findLevels(A,mp,0);
vector x;
vector<vector> ans;
int i, j;
bool left = 1, right = 0;
for(i=0;i<mp.size();i++){
x.clear();
if(left){
for(j=0;j<mp[i].size();j++){
x.push_back(mp[i][j]);
}
left = 0;
right = 1;
}
else{
for(j=mp[i].size()-1;j>=0;j–){
x.push_back(mp[i][j]);
}
left = 1;
right =0;
}
ans.push_back(x);
}
return ans;
}
`