AcWing 47. 二叉树中和为某一值的路径(DFS)
原题链接
中等
作者:
Value
,
2020-09-17 11:11:41
,
所有人可见
,
阅读 437
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
vector<int> tmp;
int sum;
void dfs(TreeNode* root, int cur){
if(root->left == NULL && root->right == NULL){
if(cur + root->val == sum){
tmp.push_back(root->val);
res.push_back(tmp);
tmp.pop_back();
}
return ;
}
tmp.push_back(root->val);
if(root->left) dfs(root->left, cur + root->val);
if(root->right) dfs(root->right, cur + root->val);
tmp.pop_back();
}
vector<vector<int>> findPath(TreeNode* root, int _sum) {
if(root == NULL) return res;
sum = _sum;
dfs(root, 0);
return res;
}
};