剑指 Offer 34. 二叉树中和为某一值的路径
解题思路:回溯法(递归先序遍历二叉树)
-. 先序遍历:按照“根、左、右”的节点遍历二叉树。
-. 记录路径:遍历节点记录路径上所有节点的和sum,当sum==target并且遍历到叶子结点,则将此路径path加入结果列表res。
算法流程:
- dfs(root, tmp,target) 函数:
- 递推参数: 当前节点 root ,当前目标值 target。
- 终止条件: 若节点 root 为空,则直接返回。
- 递推工作:
1)路径更新: 将当前节点值 root.val 加入路径 path .
2)路径和tmp更新: tmp= tmp + root.val(tmp一直加到target)
3)路径记录: 当 ① root 为叶节点(左右子节点为空) 且 ② 路径和等于目标值(tmp == target) ,则将此路径 path 加入 res 。
4)先序遍历: 递归左 / 右子节点。
5)路径恢复: 向上回溯前,需要将当前节点从路径 path 中删除,即执行 path.pop_back() 。
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
if (root == NULL) {
return res;
}
recur(root, 0,target);
return res;
}
public:
vector<vector<int>> res;
vector<int> path; //记录路径
void recur(TreeNode* root,int tmp, int target)
{
if (root == NULL) {
return;
}
tmp += root->val; // 先加
path.push_back(root->val); // 添加节点要放在 if 外面
if (tmp == target && root->left == NULL && root->right == NULL)
{
res.push_back(path);
}
recur(root->left, tmp,target);
recur(root->right,tmp, target);
path.pop_back();
}
};
- dfs(root, target) 函数:
- 递推参数: 当前节点 root ,当前目标值 target。
- 终止条件: 若节点 root 为空,则直接返回。
- 递推工作:
1)路径更新: 将当前节点值 root.val 加入路径 path .
2)路径和tmp更新: target= target - root.val(即目标值从 target 减至 0)
3)路径记录: 当 ① root 为叶节点(左右子节点为空) 且 ② 路径和等于目标值(target == 0) ,则将此路径 path 加入 res 。
4)先序遍历: 递归左 / 右子节点。
5)路径恢复: 向上回溯前,需要将当前节点从路径 path 中删除,即执行 path.pop_back() 。
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
DFS(root,target);
return res;
}
public:
//递归遍历
vector<int> volum;
vector<vector<int>> res;
void DFS(TreeNode* root,int target)
{
if(root == NULL)
return;
volum.push_back(root->val);
target -= root->val;
if(target == 0 && root->left == NULL && root->right == NULL)
{
res.push_back(volum);
}
DFS(root->left,target);
DFS(root->right,target);
//回溯之前将已加入路径的节点删除
volum.pop_back();
}
};