Simple Solution in C++


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

Log in to reply
 

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