题解 | #二叉树中和为某一值的路径(三)#

二叉树中和为某一值的路径(三)

https://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f

/*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)
 *     }
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param root TreeNode类 
 * @param sum int整型 
 * @return int整型
 */
export function FindPath(root: TreeNode, sum: number): number {
    // write code here
    if (root === null) return 0
    let count = 0
    // compute current node
    const pathCount = (root: TreeNode, sum: number): number => {
        if (root === null) return 0
        const rest = sum - root.val
        if (rest === 0) {
            count++
        }
        const leftCount = pathCount(root.left, rest)
        const rightCount = pathCount(root.right, rest)
        return count + leftCount + rightCount
    }

    // compute every node
    const allPath = (root: TreeNode, sum: number): number => {
        if (root === null) return
        pathCount(root, sum)
        allPath(root.left, sum)
        allPath(root.right, sum)
    }

    allPath(root, sum)

    return count
}


全部评论

相关推荐

买蜜雪也用卷:我觉得应该没有哪个人敢说自己熟练使用git,代码分支一复杂还是得慢慢寻思一下的,不过基本的拉代码提交代码还有分支什么的是应该会
点赞 评论 收藏
分享
点赞 评论 收藏
分享
找个工作 学历是要卡的 要求是高的 技能不足是真的 实习经验是0的 简历无处可写是事实的 钱不好赚是真的 想躺平又不敢躺 也不甘心躺 怕自己的灵感和才华被掩埋甚至从未被自己发现 又质疑自己是否真正有才华
码农索隆:你现在啊,你心里都明白咋回事,但是你没办法改变现状,一想到未来,你又没有信心狠下心来在当下努力。 得走出这种状态,不能一直困在那里面,哪不行就去提升哪,你一动不动那指定改变不了未来,动起来,积少成多才能越来越好
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务