0%

113. Path Sum II

backtracking + dfs O(n)

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
/**
* 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>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<int> v;
dfs(root, sum, v, res);
return res;
}

void dfs(TreeNode *root, int sum, vector<int> &v, vector<vector<int>> &res) {
if (!root) return;
v.push_back(root->val);
if (!root->left && !root->right) {
if (sum == root->val) {
res.push_back(v);
}
} else {
dfs(root->left, sum - root->val, v, res);
dfs(root->right, sum - root->val, v, res);
}
v.pop_back();
}
};