/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param target int整型 * @return int整型vector<vector<>> */ vector<vector<int>> res; vector<int> path; void dfs(TreeNode* node, int sum) { if (!node) return; path.push_back(node->val); sum -= node->val; if (!node->left && !node->right) { // 叶子 if (sum == 0) res.push_back(path); } else { dfs(node->left, sum); dfs(node->right, sum); } path.pop_back(); // 回溯 } vector<vector<int> > FindPath(TreeNode* root, int target) { // write code here dfs(root, target); return res; } };