AcWing 47. 二叉树中和为某一值的路径
原题链接
中等
作者:
adamXu
,
2020-10-06 08:58:29
,
所有人可见
,
阅读 353
/**
* 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> path;
int sum;
vector<vector<int>> findPath(TreeNode* root, int sum) {
//dfs深搜,dfs中传递两个参数,root,sum,当sum为0时且为叶子,
//说明当前路径合法,添加到res中,否则
//如果sum < 0则不合法,if sum > 0则继续递归
sum = sum;
dfs(root,sum);
return res;
}
void dfs(TreeNode* root, int sum){
if(!root) return;
int x = root->val;
sum -= x;
path.push_back(x);
if(!root->left && !root->right && !sum) res.push_back(path);
dfs(root->left,sum);
dfs(root->right,sum);
path.pop_back();
sum += x;
}
};