二叉树一般递归,这里注意用递减法,即递减sum的值,另外二叉树递归不要递归到最后一层的后面一层执行一些语句,容易爆栈,
可以提前存值:
代码:
/**
* 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) {
vector<vector<int>> result;
vector<int> v;
dfs(root,sum,result,v);
return result;
}
void dfs(TreeNode *root,int sum,vector<vector<int>> &result,vector<int> v){
if(!root)
return;
sum-=root->val;
v.push_back(root->val);
if(!root->left&&!root->right&&!sum){
result.push_back(v);
}
dfs(root->left,sum,result,v);
dfs(root->right,sum,result,v);
v.pop_back();
}
};