/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > tmpPaths;
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
tmpPaths.clear();clear old data
vector<int> oriPath;
find(root,sum,oriPath);
return tmpPaths;
}
void find(TreeNode *root,int sum,vector<int> tmpPath)
{
if(root==NULL)
return;
if(root->val==sum&&root->left==NULL&&root->right==NULL) //leaf
{
tmpPath.push_back(root->val);
tmpPaths.push_back(tmpPath);
tmpPath.pop_back();clear old data:when back to upper layer,pop this layer's element
}
else
{
tmpPath.push_back(root->val);
find(root->left,sum-root->val,tmpPath);
find(root->right,sum-root->val,tmpPath);
tmpPath.pop_back();clear old data:when back to upper layer,pop this layer's element
}
}
};
【leetcode】Path Sum II
最新推荐文章于 2021-11-23 19:25:16 发布