C++ 8 lines dfs solution


  • 0
    M
    class Solution {
    public:
        vector<int> largestValues(TreeNode* root) {
            vector<int> res;
            dfs(root, res, 0);
            return res;
        }
        
    private:
        void dfs(TreeNode* root, vector<int>& res, int level){
            if(!root) return;
            
            if(level == res.size()) res.push_back(INT_MIN);
            if(root->val > res[level]) res[level] = root->val;
            
            dfs(root->left, res, level + 1);
            dfs(root->right, res, level + 1);
        }
    };
    

Log in to reply
 

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