解法一-y总视频:
/**
* 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>> ans;
vector<int> path;
vector<vector<int>> findPath(TreeNode* root, int sum) {
dfs(root, 0, sum);
return ans;
}
void dfs(TreeNode* root, int sum, int target) {
if (!root) return;
path.push_back(root->val);
sum += root->val;
if (!root->left && !root->right) {
if (sum == target) ans.push_back(path);
} else {
if (root->left) dfs(root->left, sum, target);
if (root->right) dfs(root->right, sum,target);
}
path.pop_back();
}
};
可进一步优化代码如下:
来源: https://www.acwing.com/video/171/
class Solution {
public:
vector<vector<int>> ans;
vector<int> path;
vector<vector<int>> findPath(TreeNode* root, int sum) {
dfs(root, sum);
return ans;
}
void dfs(TreeNode* root, int sum) {
if (!root) return;
path.push_back(root->val);
sum -= root->val; // 用减法代替加法,可将target固定为0,减少一个传参。
if (!root->left && !root->right && !sum) ans.push_back(path); // 1.为叶子节点;2.该路径满足target为0
dfs(root->left, sum); // 省去if是因为若没有左节点,则直接return。下同
dfs(root->right, sum); // sum会一直变化
path.pop_back();
}
};
解法二-迭代:
核心思想是使用辅助栈来模拟递归的过程