Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
【问题分析】
这个问题和Path Sum类似,提高了一些要求:
1、结束条件不同,找到满足条件的路径后不能直接结束,需要继续寻找可能满足条件的路径
2、要求把找到的路径保存下来
【AC代码】
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
std::vector<int> path;
std::vector<std::vector<int> > paths;
if (root == NULL) { //返回所有结果路径集合
//paths.push_back(path);
//the key point
return paths;
}
if (root->left == NULL && root->right == NULL) { //遇到叶子节点,获取当前路径,并加入结果路径集合中
if (root->val == sum) {
path.push_back(sum);
paths.push_back(path);
}
return paths;
}
if (root->left != NULL) {
std::vector<std::vector<int> > lpaths = pathSum(root->left, sum - root->val); //获取左子节点的所有路径
for (int i = 0; i < lpaths.size(); ++i) { //将当前节点插入到每条路径的起始位置
lpaths[i].insert(lpaths[i].begin(), root->val);
paths.push_back(lpaths[i]);
}
}
if (root->right != NULL) {
std::vector<std::vector<int> > rpaths = pathSum(root->right, sum - root->val); //获取右子节点的所有路径
for (int i = 0; i < rpaths.size(); ++i) {
rpaths[i].insert(rpaths[i].begin(), root->val); //将当前节点插入到每条路径的起始位置
paths.push_back(rpaths[i]);
}
}
return paths;
}
};