思路:采用类似前序遍历的方式,停止条件是达到了叶子节点和目前路径和sum>target值,期间把满足要求的路径存入二维数组中,在归的时候记得把上一层节点删除,以及减去上一层节点的值。
class Solution {
int sum=0;
vector<int> vin;
vector<vector<int> > res;
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root==nullptr||sum>expectNumber) return res;
sum+=root->val;
vin.push_back(root->val);
bool isleaf=root->left==nullptr&&root->right==nullptr;
if(sum==expectNumber&&isleaf) {
res.push_back(vin);
}
FindPath(root->left, expectNumber);
FindPath(root->right, expectNumber);
vin.pop_back();
sum-=root->val;
return res;
}
};</int></int></int>