Skip to content

112. 路径总和 #26

Open
Open
@zpc7

Description

@zpc7

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    简单LeetCode 难度定级

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions