Skip to content

Latest commit

 

History

History
47 lines (43 loc) · 1.1 KB

113.md

File metadata and controls

47 lines (43 loc) · 1.1 KB

113. Path Sum II

Solution 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>> ans;

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

    void _pathSum(TreeNode* root, int sum, vector<int> cur_ans) {
        if (root->left == NULL && root->right == NULL) {
            if (sum == root->val) {
                cur_ans.push_back(root->val);
                ans.push_back(cur_ans);
                cur_ans.pop_back();
            }
            return;
        }
        cur_ans.push_back(root->val);
        if (root->left != NULL) {
            _pathSum(root->left, sum - root->val, cur_ans);
        }
        if (root->right != NULL) {
            _pathSum(root->right, sum - root->val, cur_ans);
        }
        cur_ans.pop_back();
        return;
    }
};