1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


void pathSum(TreeNode *n, int sum, vector<int>& nums, vector<vector<int> > &results) {
    if (n == NULL) return;

    int val = n->val;
    nums.push_back(val);
    sum -= val;
    if (n->left == NULL && n->right == NULL && sum == 0) {
        results.push_back(nums);
    } else {
        pathSum(n->left, sum, nums, results);
        pathSum(n->right, sum, nums, results);
    }    

    nums.erase(nums.end()-1);
}

vector<vector<int> > pathSum(TreeNode *root, int sum) {
    vector<vector<int> > results;
    vector<int> nums;

    pathSum(root, sum, nums, results);

    return results;
}
View Program Text


Test Status