题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void dfs(TreeNode* root, int expectNumber, vector<vector<int>>& res, vector<int> ans) {
int num = 0;
if(!root)
return;
ans.push_back(root->val);
if(!root->left && !root->right) {
for(auto x:ans)
num += x;
if(expectNumber == 0)
return;
if(num == expectNumber) {
res.push_back(ans);
ans.pop_back();
}
return;
}
dfs(root->left, expectNumber, res, ans);
dfs(root->right, expectNumber, res, ans);
}
vector<vector<int>> FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>> res;
vector<int> ans;
dfs(root, expectNumber, res, ans);
return res;
}
};