# LeetCode 113. 路徑總和 II (回溯、路徑記錄)

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sum;
vector<vector<int>> ans;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
this->sum = sum;
vector<int> list;
dfs(root,0,list);
return ans;
}
void dfs(TreeNode* root,int cnt,vector<int>&list){
if(!root){
return;
}
list.push_back(root->val);
if(!root->left && !root->right){
if(cnt+root->val==sum){
ans.push_back(list);
}
return;
}
if(root->left){
dfs(root->left,cnt+root->val,list);
list.pop_back();
}
if(root->right){
dfs(root->right,cnt+root->val,list);
list.pop_back();
}
}
};
``````

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> ans;
int sum;
vector<vector<int>> pathSum(TreeNode* root, int sum){
this->sum = sum;
vector<int> list;
if(!root){
return ans;
}
list.push_back(root->val);
dfs(root,root->val,list);
return ans;
}

void dfs(TreeNode* root,int cnt,vector<int>&list){
if(!root){
return;
}
if(!root->left && !root->right){
if(cnt==sum){
ans.push_back(list);
return;
}
}
if(root->left){
list.push_back(root->left->val);
dfs(root->left,cnt+root->left->val,list);
list.pop_back();
}
if(root->right){
list.push_back(root->right->val);
dfs(root->right,cnt+root->right->val,list);
list.pop_back();
}
}
};
``````