【leetcode 二叉树 双递归】面试题 04.12. Paths with Sum LCCI

该博客介绍了一个关于二叉树的算法问题——Path with Sum。在给定一个二叉树和一个目标和的情况下,求解有多少条路径的节点值之和等于目标和。代码中展示了使用深度优先搜索(DFS)的方法来解决此问题,通过递归遍历树的每个节点,累加路径节点值并与目标和比较,统计符合条件的路径数量。
摘要由CSDN通过智能技术生成

面试题 04.12. Paths with Sum LCCI

在这里插入图片描述

/**
 * 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:
    void DFS(TreeNode* root, int sum, int now_sum, int &cnt) {
        if(!root) return ;
        now_sum += root->val;
        if(now_sum == sum) cnt++;
        if(root->left) DFS(root->left, sum, now_sum, cnt);
        if(root->right) DFS(root->right, sum, now_sum, cnt);
    }
    int pathSum(TreeNode* root, int sum) {
        if(!root) return 0;
        int cnt = 0;
        DFS(root, sum, 0, cnt);
        return cnt + pathSum(root->left, sum) + pathSum(root->right, sum);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值