Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

路径总和 #296

Open
Sunny-117 opened this issue Nov 8, 2022 · 2 comments
Open

路径总和 #296

Sunny-117 opened this issue Nov 8, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@lxy-Jason
Copy link
Contributor

/**
 * @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);
};

@coffeeAndTeaa
Copy link

coffeeAndTeaa commented Jan 21, 2023

`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);

}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants