题目链接:https://leetcode-cn.com/problems/path-sum-ii/solution/
解法1:回溯
与112题一样的思路,这次记录下走过的节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { private: vector<vector<int>> res; vector<int> temp; public: vector<vector<int>> pathSum(TreeNode* root, int sum) { ok(root,sum); return res; } void ok(TreeNode *root,int sum) { if(root==NULL) { return ; } temp.push_back(root->val); if(sum-root->val==0&&root->left==NULL&&root->right==NULL) { res.push_back(temp); return ; } if(root->left!=NULL) { ok(root->left,sum-(root->val)); temp.pop_back(); } if(root->right!=NULL) { ok(root->right,sum-(root->val)); temp.pop_back(); } return ; } };
|