Find Largest Value in Each Tree Row (C++ finds the largest value in each tree row)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    map<int,int> mp;
public:
    void helper(TreeNode *root,int h) {
        if(!root) return;
        if(mp.find(h)==mp.end()) mp[h]=root->val;
        else mp[h]=max(mp[h],root->val);
        helper(root->left,h+1);
        helper(root->right,h+1);
    }
    
    vector<int> largestValues(TreeNode* root) {
        helper(root,0);
        vector<int> v;
        for(auto it=mp.begin();it!=mp.end();it++) v.push_back(it->second);
        return v;
    }
};

 

Guess you like

Origin blog.csdn.net/coolsunxu/article/details/114937613