Why the code is so slow? How can I improve it?


  • 0
    V
    class Solution {
    private:
        vector<int> temp;
        vector<vector<int>> result;
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            if( !root )
                return vector<vector<int>>();
        
            temp.push_back( root->val );
            if( !root->left && !root->right )
                if( sum == root->val )
                    result.push_back( temp );
     
            pathSum( root->left, sum - root->val );
            pathSum( root->right, sum - root->val );
            temp.pop_back();
            return result;
        }
    };

  • 0
    G

    The code is slow because pathSum returns a copy of "result", instead of a reference to it. I don't think you can improve it without changing the return type of pathSum.


Log in to reply
 

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