#include <vector>
using std::vector;
class Solution {
private:
void get_sum(TreeNode *root, vector<int> path, int sum, vector<vector<int>> &res, int targetSum) {
sum += root->val;//回溯被隐藏起来了
path.push_back(root->val);//回溯被隐藏起来了,因为函数里的path改变了,没有改变函数外的path
if (root->left == nullptr && root->right == nullptr) {
if (sum == targetSum) {
res.push_back(path);
return;
}
else
return;
}
if (root->left != nullptr)
get_sum(root->left, path, sum, res, targetSum);
if (root->right != nullptr)
get_sum(root->right, path, sum, res, targetSum);
return;
}
public:
vector<vector<int>> pathSum(TreeNode *root, int targetSum) {
vector<vector<int>> res;
vector<int> path;
if (root == nullptr)
return res;
get_sum(root, path, 0, res, targetSum);
return res;
}
};
标签:ii,res,sum,II,vector,targetSum,path,root
From: https://www.cnblogs.com/zwyyy456/p/16648990.html