题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
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) {
if(!root)
return;
ans.push_back(root->val);
num += root->val;
if(!root->left && !root->right) {
if(num == expectNumber) {
res.push_back(ans);
num -= ans.back();
ans.pop_back();
}
return;
}
dfs(root->left, expectNumber, res, ans, num);
dfs(root->right, expectNumber, res, ans, num);
}
vector<vector<int>> FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>> res;
vector<int> ans;
int num = 0;
dfs(root, expectNumber, res, ans, num);
return res;
}
};