首页 > 技术文章 > LeetCode 113. 路径总和 II C++

p1967914901 2020-05-13 10:06 原文

提交结果:内存超100%,用时超69%

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<int> s ;
        vector<vector<int> > result;
        int path_value = 0;
        preorder(root,sum,s,path_value,result);
        return result;
    }
    void preorder(TreeNode* root,int sum,vector<int> &s,
                int path_value,vector<vector<int> > &result){
                if(!root) return;
                s.push_back(root->val);
                path_value +=root->val;
                if(!root->left &&!root->right && sum ==path_value){
                    result.push_back(s);
                }
                preorder(root->left ,sum,s,path_value,result);
                
                preorder(root->right,sum,s,path_value,result);
                path_value -= root->val;
                s.pop_back();
    }
};

推荐阅读