遍历一遍树的节点,沿节点依次向下递增,回溯的时候,记得恢复现场
/**
* 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;
vector<int> path;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
dfs(root, sum);
return ans;
}
void dfs(TreeNode* root, int sum)
{
if(!root) return ;
path.push_back(root->val);
sum -= root -> val;
//判断当前节点是不是叶子节点,并且是否满足sum=0
if(!root -> left && !root -> right && !sum) ans.push_back(path);
//递归处理左右子树
dfs(root -> left, sum);
dfs(root -> right, sum);
//path还原
path.pop_back();
}
};
原文:https://www.cnblogs.com/Trevo/p/12715097.html