剑指 Offer 34. 二叉树中和为某一值的路径

本文讲解了如何使用递归的回溯法解决二叉树中和为特定值的路径问题。通过先序遍历,记录路径和,当路径和等于目标值且到达叶子节点时,将路径存入结果列表。两种实现方式对比,包括DFS和先序遍历的递归策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

剑指 Offer 34. 二叉树中和为某一值的路径

在这里插入图片描述
解题思路:回溯法(递归先序遍历二叉树)

-. 先序遍历:按照“根、左、右”的节点遍历二叉树。
-. 记录路径:遍历节点记录路径上所有节点的和sum,当sum==target并且遍历到叶子结点,则将此路径path加入结果列表res。

算法流程:

  1. dfs(root, tmp,target) 函数:
  2. 递推参数: 当前节点 root ,当前目标值 target。
  3. 终止条件: 若节点 root 为空,则直接返回。
  4. 递推工作:
    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();
    }
};
  1. dfs(root, target) 函数:
  2. 递推参数: 当前节点 root ,当前目标值 target。
  3. 终止条件: 若节点 root 为空,则直接返回。
  4. 递推工作:
    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();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值