-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path113.path-sum-ii.cpp
52 lines (46 loc) · 1.41 KB
/
113.path-sum-ii.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* @lc app=leetcode id=113 lang=cpp
*
* [113] Path Sum II
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <stack>
#include <unordered_map>
#include <utility>
#include <vector>
#include <numeric>
using namespace std;
class Solution {
public:
void visit(TreeNode* root, int sum, vector<int> sumVector, vector<vector<int>>& answer) {
sumVector.push_back(root->val);
cout << accumulate(sumVector.begin(), sumVector.end(), 0) << endl;
if (root->left == nullptr && root->right == nullptr && accumulate(sumVector.begin(), sumVector.end(), 0) == sum)
{
answer.push_back(sumVector);
}
if (root->left != nullptr) visit(root->left, sum, sumVector, answer);
if (root->right != nullptr) visit(root->right, sum, sumVector, answer);
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> answer;
if (root == nullptr) return answer;
visit(root, sum, vector<int> {}, answer);
return answer;
}
};
// @lc code=end