You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode 112路径Sum问题:递归中currSum无法累加求助

LeetCode 112. Path Sum 问题排查

你的代码核心错误在于递归调用时用错了函数:在helper函数的最后一行,你调用的是hasPathSum而非helper。

hasPathSum函数的逻辑是从头初始化currSum=0再调用helper,所以每次递归分支都会重置累加值为0,导致currSum始终是0 + 当前节点值,无法实现路径上的累加。

修正后的代码

var hasPathSum = function(root, targetSum) {
    var result = helper(root, targetSum, 0);
    return result;
};

function helper(root, targetSum, currSum){
    if(root === null) return false;

    currSum = currSum + root.val;
    console.log(currSum);

    if(root.left === null && root.right === null && currSum === targetSum){
        return true;
    }

    // 改为调用helper,传递累加后的currSum
    return helper(root.left, targetSum, currSum) || helper(root.right, targetSum, currSum);
}

修正后,递归时会正确传递每次累加后的currSum,就能得到你预期的累加输出了。

内容的提问来源于stack exchange,提问作者eedideyahoocom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:20:26