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] ]
DFS:
void findPathSum(TreeNode* root, vector<int> &path, vector<vector<int>> &allpath, int sum)
{
path.push_back(root->val);
if(root->left == NULL && root->right == NULL){
vector<int>::iterator it = path.begin();
int tmpsum = 0;
for(; it != path.end(); ++it)
tmpsum += *it;
if(tmpsum == sum){
allpath.push_back(path);}
path.pop_back();
return;
}
if(root->left)
findPathSum(root->left,path,allpath,sum);
if(root->right)
findPathSum(root->right,path,allpath,sum);
path.pop_back();
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> allpath;
if(root == NULL)
return allpath;
vector<int> path;
findPathSum(root, path, allpath, sum);
return allpath;
}

1100

被折叠的 条评论
为什么被折叠?



