vertical traversal of binary tree gfg practice code example

Example: vertical traversal of binary tree gfg

void getVerticalOrder(TreeNode* root, int hd, map<int, vector<int>> &mp)
{
    // Base case
    if (root == NULL)
        return;
 
    mp[hd].push_back(root->val);
    getVerticalOrder(root->left, hd-1, mp);
    getVerticalOrder(root->right, hd+1, mp);
}
    vector<vector<int>> verticalTraversal(TreeNode* root) {
     map < int,vector<int> > mp;
    int hd = 0;
    getVerticalOrder(root, hd,mp);
        vector<vector<int>>ans;
        
        for (auto it=mp.begin(); it!=mp.end(); it++)
        { 
            vector<int> v;
        for (int i=0; i<it->second.size(); ++i)
            v.push_back(it->second[i]);
    //    cout << endl;
         ans.push_back(v);
         }
        
    return ans;
    }

Tags:

Misc Example