LetCode 113. 路径总和 II

/**
 * 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<vector<int>> res;
        vector<int> tmp;
        if (root == NULL)
            return res;
        hasPathSum(root, 0, sum, res, tmp);
        return res;
    }
    
    void hasPathSum(TreeNode* root, int sum, int target, vector<vector<int>>& res, vector<int>& tmp){
        if (root == NULL)
            return;
        if (root->left == NULL && root->right == NULL && sum + root->val == target){
            tmp.push_back(root->val);
            res.push_back(tmp);
            tmp.pop_back();
            return;
        }
        tmp.push_back(root->val);
        hasPathSum(root->left, root->val + sum, target, res, tmp);
        hasPathSum(root->right, root->val + sum, target, res, tmp);
        tmp.pop_back();
    }
};
static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();

猜你喜欢

转载自blog.csdn.net/wbb1997/article/details/81089406