dfs,跟Path Sum I 相差无几。
/**
* Definition for binary tree
* 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) {
ans.clear();
dfs(root, sum, 0);
return ans;
}
void dfs(TreeNode *root, int sum, int cnt){
if(!root) return ;
if(!root->left && !root->right){
if(cnt + root->val == sum){
v.push_back(root->val);
ans.push_back(v);
v.pop_back();
}
return ;
}
v.push_back(root->val);
dfs(root->left, sum, cnt+root->val);
dfs(root->right, sum, cnt+root->val);
v.pop_back();
}
vector<int> v;
vector<vector<int> > ans;
};