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

112. 路径总和 #28

Closed
sailei1 opened this issue May 20, 2019 · 0 comments
Closed

112. 路径总和 #28

sailei1 opened this issue May 20, 2019 · 0 comments

Comments

@sailei1
Copy link
Owner

sailei1 commented May 20, 2019

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

解法
途径节点 相减 跟节点值 做匹配
注意 叶子节点是指没有子节点的节点。

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} sum
 * @return {boolean}
 */
var hasPathSum = function(root, sum) {
     let left = false, right = false; 
        if(root) {
            sum -= root.val;//途径节点 相减 缩小范围
            if(root.left) {left = hasPathSum(root.left, sum);}
            if(root.right){ right = hasPathSum(root.right, sum);}
            if(!root.left && !root.right && sum == 0) { //确定节点没有子节点 
               return true;
            }
        }
    return left || right;
};

// let hasPathSum = function(root, sum) {
//     if(!root) return false;
//     if(root.left === null  && root.right === null) return sum === root.val;
//     return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
// };
//思路跟上边一样,少减一次
@sailei1 sailei1 closed this as completed May 20, 2019
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

1 participant