题解 | 二叉树中和为某一值的路径(二)
二叉树中和为某一值的路径(二)
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
vector<vector<int>> ans;
vector<int> path;
void dfs(TreeNode* root, int& target, int sum) {
path.emplace_back(root->val);
sum += root->val;
if (sum == target && !root->left && !root->right) ans.emplace_back(path);
if (root->left) dfs(root->left, target, sum);
if (root->right) dfs(root->right, target, sum);
path.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root, int target) {
if (!root) return {};
// write code here
dfs(root, target, 0);
return ans;
}
};

查看18道真题和解析