113. Path Sum II

Medium

100636FavoriteShare

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

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]
]
class Solution {
private:
vector<vector<int>> result;
int score;
public:
vector<vector<int>> pathSum(TreeNode* root, int sum)
{
score = sum;
if(root == NULL){return result;}
vector<int> tmp;
dfs(root,tmp,0);
return result;
}
void dfs(TreeNode *root,vector<int> tmp,int sum)
{
tmp.push_back(root->val);
sum += root->val;
if(root->left == NULL && root->right == NULL && sum == score){result.push_back(tmp);}
if(root->left != NULL){dfs(root->left,tmp,sum);}
if(root->right != NULL){dfs(root->right,tmp,sum);}
}
};