AcWing 47. 二叉树中和为某一值的路径
原题链接
中等
作者:
回归线
,
2021-04-25 14:09:00
,
所有人可见
,
阅读 314
/**
* 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 {
private:
vector<int> path;
vector<vector<int>> ans;
public:
vector<vector<int>> findPath(TreeNode* root, int sum) {
dfs(root, sum);
return ans;
}
void dfs(TreeNode* root, int sum) {
if (!root) {
return;
}
path.push_back(root->val);
sum -= root->val;
if (!root->left && !root->right && !sum) {
ans.push_back(path);
}
dfs(root->left, sum);
dfs(root->right, sum);
path.pop_back();
}
};