Sunny-117/js-challenges

路径总和

Sunny-117 opened this issue · 2 comments

路径总和
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {boolean}
 */
var hasPathSum = function(root, targetSum) {
    function backtracking(root,sum){ //回溯
        if(sum === 0 && !root.left && !root.right){ 
            return true;
        }
        if(!root.left && !root.right) return false;
        if(root.left && backtracking(root.left,sum - root.left.val)) return true;
        if(root.right && backtracking(root.right,sum - root.right.val)) return true;
        return false;
    }
    if(!root) return false;
    return backtracking(root,targetSum - root.val);
};

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

var helper = function(root, pathSum, target) {
if (root == undefined) {
return false;
}

if (root.left == undefined && root.right == undefined) {
    return (root.val + pathSum) === target;
}

let currentSum = root.val + pathSum;
return helper(root.left, currentSum, target) || helper(root.right, currentSum, target);

}`