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]
]
题解:寻找与目标值相等的路径,并输出来,这是一个深度优先遍历问题,沿着一条路径一直走到底,直到为叶节点,判断整个路径的值是否等于目标值,若想等加入到输出的paths集合中,因为我们要使用递归函数,所以,只能构造一个辅助递归函数,否则每一次都要输出paths集合太浪费时间;
class Solution {
private:
vector<vector<int>> paths;
vector<int> path;
void helppathSum(TreeNode* root,int sum){
path.push_back(root->val);
if(root->left == NULL && root->right == NULL && sum == root->val ){
paths.push_back(path);
}
if(root->left != NULL) helppathSum(root->left,sum - root->val);
if(root->right != NULL) helppathSum(root->right,sum - root->val);
path.pop_back();
}
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(root == NULL) return paths;
helppathSum(root,sum);
return paths;
}
};
结果: