Leetcode 113. Path Sum II | | Leetcode 113. Path Sum II 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution2.1 Recursive Version 1 12345678910111213141516171819202122232425262728293031323334/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> result; if(!root) { return result; } vector<int> path; tranverseTree(root, sum, result, path); return result; } void tranverseTree(TreeNode* root, int sum, vector<vector<int>>& result, vector<int> path) { path.push_back(root->val); if(root->val == sum && root->left == NULL && root->right == NULL) { result.push_back(path); } if(root->left) { tranverseTree(root->left, sum - root->val, result, path); } if(root->right) { tranverseTree(root->right, sum - root->val, result, path); } }}; Version 2 12345678910111213141516171819202122232425262728293031323334353637/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> result; if(!root) { return result; } vector<int> path; tranverseTree(root, sum, result, path); return result; } void tranverseTree(TreeNode* root, int sum, vector<vector<int>>& result, vector<int>& path) { path.push_back(root->val); if(root->val == sum && root->left == NULL && root->right == NULL) { result.push_back(path); path.pop_back(); return; } if(root->left) { tranverseTree(root->left, sum - root->val, result, path); } if(root->right) { tranverseTree(root->right, sum - root->val, result, path); } path.pop_back(); }}; Reference https://leetcode.com/problems/path-sum-ii/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏