113. 路径总和 II/C++

113. 路径总和 II/C++_第1张图片
回溯法

/**
 * 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>> res;
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<int> cur;
        dfs(root,cur,sum);
        return res;
    }
    void dfs(TreeNode* root, vector<int>& cur, int target){
        if(!root) return;
        int newTarget = target - root->val;
        if(!root->left && !root->right && newTarget==0){
            cur.push_back(root->val);
            res.push_back(cur);
            cur.pop_back();
        }
        cur.push_back(root->val);
        dfs(root->left,cur,newTarget);
        dfs(root->right,cur,newTarget);
        cur.pop_back();
    }
};

你可能感兴趣的:(回溯法,LeetCode/C++)