我們可以利用 112 的做法,只是多用一個 vector 來記錄答案,用一個 vector 來記錄 path,只要每次發現 path sum 滿足,就把路徑加入答案。
Copy /**
* 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) {
if(!root) return res;
vector<int> path;
findPath(root, sum, path);
return res;
}
private:
vector<vector<int>> res;
void findPath(TreeNode* root, int sum, vector<int> path) {
if(!root) return;
path.push_back(root->val);
if(!root->left && !root->right && root->val == sum) {
res.push_back(path);
return;
}
findPath(root->left, sum-root->val, path);
findPath(root->right, sum-root->val, path);
path.pop_back();
return;
}
};
Runtime: 32 ms, faster than 27.81% of C++ online submissions for Path Sum II. Memory Usage: 38.3 MB, less than 10.73% of C++ online submissions for Path Sum II.
Copy class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<int> path;
findPath(root, sum, path, res);
return res;
}
private:
void findPath(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &res) {
if(!root) return;
path.push_back(root->val);
if(!root->left && !root->right && root->val == sum)
res.push_back(path);
findPath(root->left, sum-root->val, path, res);
findPath(root->right, sum-root->val, path, res);
path.pop_back();
}
};
Runtime: 12 ms, faster than 95.70% of C++ online submissions for Path Sum II. Memory Usage: 20 MB, less than 54.29% of C++ online submissions for Path Sum II.