题目描述
原题链接:113. 路径总和 II
解题思路
设置一个path
存当前路径,设置一个res
存结果集。
一、当前遍历,添加当前元素
此方式是,每次遍历时候,将当前结果添加到path
当中,若找到和为targetSum
的,则输出,否则分别再向左子树、右子树探测。函数结尾时候,再把添加的这个结点pop
。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
void traversal(TreeNode* root, int targetSum, vector<int> path) {
// 遍历到一次加入加入该节点
path.push_back(root->val);
targetSum -= root->val;
if(!root->left && !root->right) {
if(targetSum == 0) {
res.push_back(path);
return ;
}
}
if(root->left) {
traversal(root->left, targetSum, path);
}
if(root->right) {
traversal(root->right, targetSum, path);
}
// 注意pop当前节点要放到最后,而不是左一次右一次,否则会出现重复弹出
path.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(!root) return {};
vector<int> path;
traversal(root, targetSum, path);
return res;
}
};
二、当前遍历,添加未来元素
此方式是,每次判定出左子树或右子树为空时,就提前将该结果加入path
当中,退出时候,再分别从退出口pop
先加入的元素。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
void traversal(TreeNode* root, int targetSum, vector<int> path) {
if(!root->left && !root->right) {
if(targetSum == 0) {
res.push_back(path);
return ;
}
}
if(root->left) {
path.push_back(root->left->val); // 遍历此结点
traversal(root->left, targetSum - root->left->val, path);
path.pop_back(); // 弹出加入结点
}
if(root->right) {
path.push_back(root->right->val);
traversal(root->right, targetSum - root->right->val, path);
path.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(!root) return {};
vector<int> path;
path.push_back(root->val);
traversal(root, targetSum - root->val, path);
return res;
}
};