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