Zheaoli / do-something-right

MIT License
37 stars 3 forks source link

2022-10-19 #395

Open Zheaoli opened 1 year ago

Zheaoli commented 1 year ago

2022-10-19

Dapeus commented 1 year ago

image

gongpeione commented 1 year ago
/*
 * @lc app=leetcode id=112 lang=typescript
 *
 * [112] Path Sum
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
    const walk = (node, prevVal = 0) => {
        if (!node) return false;

        const val = prevVal + node.val;
        if (!node.left && !node.right && val === targetSum) return true;

        return walk(node.left, val) || walk(node.right, val);
    }

    return walk(root);
};
// @lc code=end

微信id: 弘树 来自 vscode 插件