A very quick (12ms), tidy C++ solution with DFS


  • 1
    T
    class Solution {
    public:
        vector<int> largestValues(TreeNode* root) {
            vector<int> ret;
            if (root == nullptr) {
                return ret;
            }
            dfs(root, 0, ret);
            return ret;
        }
        
    private:
        void dfs(const TreeNode* root, const int depth, vector<int>& res) {
            if (root == nullptr) {
                return;
            }
            if (depth == res.size()) {
                res.push_back(root->val);
            } else {
                res[depth] = max(res[depth], root->val);
            }
            dfs(root->left, depth + 1, res);
            dfs(root->right, depth + 1, res);
        }
    };
    

Log in to reply
 

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