题目描述
dfs+回溯,path存储当前方案
C++ 代码
class Solution {
public:
vector<vector<int>> res;
int target;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> path;
target = sum;
dfs(root, 0, path);
return res;
}
void dfs(TreeNode* root, int s, vector<int>& path)
{
if (!root) return;
path.push_back(root->val);
s += root->val;
if (s == target && !root->left && !root->right) res.push_back(path);
dfs(root->left, s, path);
dfs(root->right, s, path);
path.pop_back();
}
};