AcWing 47. 二叉树中和为某一值的路径
原题链接
中等
作者:
adamXu
,
2020-09-27 13:17:07
,
所有人可见
,
阅读 414
/**
* 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:
int sum;
vector<vector<int >> res;
vector<int> path;
vector<vector<int>> findPath(TreeNode* root, int sum) {
//思路,深搜,如果搜索到叶子节点且sum == 0,当前路径合法,加入到res中,否则不合法,直接return
//深搜中注意保护原来现场,所以有pop_back
sum = sum;
dfs(root,sum);
return res;
}
void dfs(TreeNode* root,int sum){
if(!root) return;
path.push_back(root->val);
sum -= root->val;
if(!root->left && !root->right && !sum) res.push_back(path);
dfs(root->left,sum);
dfs(root->right,sum);
path.pop_back();
}
};