113. Path Sum II

题目链接

https://leetcode.com/problems/path-sum-ii/

代码

class Solution {
public:
    void dfs(TreeNode *pNode, vector> &ans, vector &v, int sum, int target) {
        sum += pNode->val;
        v.push_back(pNode->val);
        if (pNode->right == NULL && pNode->left == NULL) {
            if (sum == target) {
                ans.push_back(v);
            }
        } else {
            if (pNode->left != NULL) {
                dfs(pNode->left, ans, v, sum, target);
            }
            if (pNode->right != NULL) {
                dfs(pNode->right, ans, v, sum, target);
            }
        }
        
        v.pop_back();
    }

    vector> pathSum(TreeNode* root, int sum) {
        vector> ans;
        if (root == NULL) {
            return ans;
        }

        vector v;
        dfs(root, ans, v, 0, sum);
        return ans;
    }
};

你可能感兴趣的:(113. Path Sum II)