12 ms, beats 80% of c++ solution


  • 0
    R
    class Solution {
    public:
        vector<vector<int> > ans;
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            path(root,sum);
            return ans;
        }
        vector<int> level;
        void path(TreeNode *root,int sum)
        {
            if(root==NULL)
              return ;
            level.push_back(root->val);
            path(root->left,sum);
            path(root->right,sum);
            
            if(root->left==NULL and root->right==NULL)
            {
                int total=0;
                for(int i=0;i<level.size();i++)
                   total+=level[i];
                if(total==sum)
                ans.push_back(level);
            }
            level.pop_back();
        }
    };

Log in to reply
 

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