二叉树中和为某一值的路径
回溯法本质是一个基于 DFS 的穷举过程:先添加值,再判定现有结果是否满足条件,执行 DFS,最后回退。
class Solution {
public:
vector<vector<int>> ret;
vector<int> path;
vector<vector<int>> FindPath(TreeNode* root, int target) {
if(!root) return ret;
dfs(root, target);
return ret;
}
void dfs(TreeNode* root, int target){
path.emplace_back(root->val);
target -= root->val;
if(!root->left && !root->right && !target)
ret.emplace_back(path);
else{
if(root->left) dfs(root->left, target);
if(root->right) dfs(root->right, target);
}
path.pop_back();
}
};
二叉树中和为某一值的路径(任意路径)
若需查找所有路径上节点和等于目标值的路径个数,且起点任意,可遍历二叉树的所有节点作为起点。查找路径时继续前序遍历子树,遇到节点 sum 相应减少,sum==0 则找到一种情况。因数值有正有负,不能直接退出,需继续遍历左右子树。
class Solution {
public:
int ret = 0;
void dfs(TreeNode* root, int sum) {
if (!root) return;
sum -= root->val;
if (sum == 0) ++ret;
(root->left, sum);
(root->right, sum);
}
{
(!root) ;
(root, sum);
(root->left, sum);
(root->right, sum);
ret;
}
};


