113. Path Sum II

2019-06-14  本文已影响0人  jecyhw

题目链接

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

代码

class Solution {
public:
    void dfs(TreeNode *pNode, vector<vector<int>> &ans, vector<int> &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<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> ans;
        if (root == NULL) {
            return ans;
        }

        vector<int> v;
        dfs(root, ans, v, 0, sum);
        return ans;
    }
};
上一篇下一篇

猜你喜欢

热点阅读