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. 路径总和 #26

Open
zpc7 opened this issue Aug 7, 2022 · 0 comments
Open

112. 路径总和 #26

zpc7 opened this issue Aug 7, 2022 · 0 comments
Labels
简单 LeetCode 难度定级

Comments

@zpc7
Copy link
Owner

zpc7 commented Aug 7, 2022

112. 路径总和

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {boolean}
 */
var hasPathSum = function (root, targetSum) {
    const pathSum = (node, sum) => {
        if (node === null) return false;  // 节点为空, 返回false
        if (node.left === null && node.right === null) { // 到达了叶子节点, 也就是路径的终点, 判断是否满足
            return sum + node.val === targetSum;
        }
        sum += node.val; // 累加
        return pathSum(node.left, sum) || pathSum(node.right, sum) // 左右子树 || 的关系
    }

    return pathSum(root, 0)
};
@zpc7 zpc7 added 简单 LeetCode 难度定级 JS and removed JS labels Aug 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
简单 LeetCode 难度定级
Projects
None yet
Development

No branches or pull requests

1 participant