Leetcode 515. Find Largest Value in Each Tree Row

https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/


跟上一题一样,直接开数组记录就行


class Solution {
public:
    void dfs( TreeNode* root, int cur_dep,  vector &ans) {
        if (!root) return;
        if (cur_dep == ans.size()) {
            ans.push_back( root->val );
        } else {
            ans[cur_dep] = max(ans[cur_dep], root->val);
        }
        dfs(root->left, cur_dep+1, ans);
        dfs(root->right, cur_dep+1, ans);
    }
    
    vector largestValues(TreeNode* root) {
        vector ans;
        dfs(root, 0, ans);
        return ans;
    }
};

你可能感兴趣的:(LeetCode题解)