- - 水题, 继续模拟, 练习指针
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
vector<vector<int> > ans;
vector<int> stk;
void dfs(TreeNode * root, int sum){
stk.push_back(root->val);
if(root->left == 0 && root->right == 0){
if(root->val == sum){
ans.push_back(stk);
}
}
if(root->left != 0)
dfs(root->left, sum - root->val);
if(root->right != 0)
dfs(root->right, sum - root->val);
stk.pop_back();
}
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ans.clear();
stk.clear();
if(root == 0)
return ans;
dfs(root, sum);
return ans;
}
};