AcWing 47. 二叉树中和为某一值的路径
原题链接
中等
作者:
梵高先生
,
2020-05-15 17:20:08
,
所有人可见
,
阅读 708
C++ 代码
/**
* 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> temp;
vector<vector<int>> findPath(TreeNode* root, int sum) {
if(root == NULL) return res;
dfs(root,sum);
return res;
}
void dfs(TreeNode * r, int sum){
if(r->left == NULL && r->right == NULL){
sum -= r->val;
temp.push_back(r->val);
if(sum == 0){
res.push_back(temp);
}
//回溯
temp.pop_back();
return ;
}
//非叶子节点
sum -= r->val;
temp.push_back(r->val);
if(r->left) dfs(r->left,sum);
if(r->right) dfs(r->right,sum);
temp.pop_back();
return ;
}
};