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
相关产品推荐
相关产品推荐

