C++ group by height


  • 0
    B

    idea is simple, the output are actually grouped by their height. So we just need to find its height and store it somewhere or directly update the result.

    class Solution {
    public:
        unordered_map<int,vector<int>>mp;
        vector<vector<int>> findLeaves(TreeNode* root) {
            vector<vector<int>> result;
            if(!root) return result;
            height(root, mp);
            for(int i = 1; i <= mp.size(); i++) result.push_back(mp[i]);
            return result;
        }
        
        int height( TreeNode * root, unordered_map<int,vector<int>> & mp)
        {
            if(!root) return 0;
            int h = max(height(root -> left, mp), height(root -> right, mp)) + 1;
            mp[h].push_back(root -> val);
            return h;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.