Is there any map in C++ which can store duplicate values and in same order as order of insertion?

Viewed 58

I am trying to code solution for this Diagonal Traversal of Binary Tree. I got easy solutions from editorial, but want to improve my code. I am using multimap but insertion order is not preserved.

Is there any map in c++ where I can store duplicate value and in the order of insertion. I tried using unordered_multimap but does not works

vector<int> diagonal(Node *root)
{
    vector<int>v;
    if(root == NULL){
        return v;
    }
    
    queue<pair<Node*,int>>q;
    int level = 0;
    unordered_multimap<int,int>mp;
    
    q.push({root,level});
    
    mp.insert(pair<int, int>(root->data,level));
    q.push({NULL,0});
    
    while(!q.empty()){
        // pair<int,int> p = q.front();
        Node *f = q.front().first;
        int h = q.front().second;
        
        q.pop();
        
    if(f == NULL){
            if(!q.empty()){
            q.push({NULL,0});
        }
    }
        
    else{
     
       if(f->left){
           
        q.push({f->left,h+1});
        mp.insert(pair<int, int>(f->left->data,h+1));
        if(h+1 > level)
        level = h+1;
        
        }
        
        if(f->right){
        q.push({f->right,h});
        mp.insert(pair<int, int>(f->right->data,h));
        }
        }
        }
        
        
        for(int i = 0; i <= level+1; i++){
            
            for(auto itr = mp.begin(); itr != mp.end(); itr++){
                if(itr->second == i){
                v.push_back(itr->first);
                
                }
            }
            
        }
      return v;  
        
    }
    

The output of this code : Results

I want to print the nodes in right order, as in expected outcome. If any other data structure can help instead of maps, that will also be okay.

Thanks in advance

0 Answers
Related