原题链接
子母题 112 Path Sum
跟112多了一点就是保存路径
依然用dfs,多了两个vector保存路径
Runtime: 16 ms, faster than 16.09% of C++
class Solution
{
public:
vector<vector<
int>>
res;
vector<
int>
temp;
vector<vector<
int>> pathSum(TreeNode *root,
int sum)
{
dfs(root,temp,0,sum);
return res;
}
void dfs(TreeNode *root, vector<
int> cur,
int total,
int sum)
{
if (root ==
NULL)
return;
total += root->
val;
cur.push_back(root->
val);
if (root->left == NULL && root->right ==
NULL)
{
if (total ==
sum)
{
res.push_back(cur);
}
return;
}
if (root->
left)
dfs(root->
left, cur, total, sum);
if (root->
right)
dfs(root->
right, cur, total, sum);
}
};
转载于:https://www.cnblogs.com/ruoh3kou/p/9931374.html
相关资源:数据结构—成绩单生成器