美文网首页
113. Path Sum II

113. Path Sum II

作者: jecyhw | 来源:发表于2019-06-14 06:30 被阅读0次

    题目链接

    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;
        }
    };
    

    相关文章

      网友评论

          本文标题:113. Path Sum II

          本文链接:https://www.haomeiwen.com/subject/ofmyfctx.html