113. 路径总和 II
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution 11 { 12 vector<vector<int>> ans; 13 vector<int> out; 14 public: 15 vector<vector<int>> pathSum(TreeNode* root, int sum) 16 { 17 int target = 0; 18 solve(root,sum,target); 19 return ans; 20 } 21 22 void solve(TreeNode* root, int sum,int target) 23 { 24 if(!root) return; 25 out.push_back(root->val); 26 target += root->val; 27 28 if(root->left == NULL && root->right == NULL && target == sum) 29 { 30 ans.push_back(out); 31 out.pop_back(); 32 return; 33 } 34 solve(root->left,sum,target); 35 solve(root->right,sum,target); 36 37 out.pop_back(); 38 target -= root->val; 39 } 40 };
Mamba never out

浙公网安备 33010602011771号