【LeetCode】113. Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
Solution 1
1 class Solution { 2 public: 3 vector<vector<int>> pathSum(TreeNode* root, int sum) { 4 vector<vector<int>> res; 5 vector<int> cur; 6 if (!root) 7 return res; 8 9 dfs(res, cur, root, sum); 10 return res; 11 } 12 13 void dfs(vector<vector<int>>& res, vector<int>& cur, TreeNode* root, int sum) { 14 if (!root) { 15 return; 16 } 17 cur.push_back(root->val); 18 if (!root->left && !root->right && root->val == sum) { 19 20 res.push_back(cur); 21 cur.pop_back(); 22 return; 23 } 24 dfs(res, cur, root->left, sum - root->val); 25 dfs(res, cur, root->right, sum - root->val); 26 cur.pop_back(); 27 } 28 29 };
Solution 2
1 class Solution { 2 public: 3 vector<vector<int>> pathSum(TreeNode* root, int sum) { 4 vector<vector<int>> res; 5 vector<TreeNode*> path; 6 TreeNode* cur = root, *pre = nullptr; 7 int val = 0; 8 while (cur || !path.empty()) { 9 while (cur) { 10 path.push_back(cur); 11 val += cur->val; 12 cur = cur->left; 13 } 14 cur = path.back(); 15 if (!cur->left && !cur->right && val == sum) { 16 res.push_back({}); 17 for(auto it : path) { 18 res.back().push_back(it->val); 19 } 20 } 21 if (cur->right && cur->right != pre) 22 cur = cur->right; 23 else { 24 pre = cur; 25 val -= cur->val; 26 path.pop_back(); 27 cur = nullptr; 28 } 29 } 30 return res; 31 } 32 };