美文网首页
剑指 Offer II 050. 向下的路径节点之和

剑指 Offer II 050. 向下的路径节点之和

作者: 邦_ | 来源:发表于2022-06-30 11:23 被阅读0次

func pathSum(_ root: TreeNode?, _ targetSum: Int) -> Int {

        if root == nil {
            return 0
        }
        var ret = rootSum(root, targetSum)
        ret += pathSum(root?.left, targetSum)
        ret += pathSum(root?.right, targetSum)
        return ret
        
    }
    
    func rootSum(_ node: TreeNode?,_ targetSum: Int) -> Int {
        if node == nil {
            return 0
        }
        var ret = 0
        let value = (node?.val)!
        if value == targetSum {
            ret += 1
        }
        
        ret += rootSum(node?.left, targetSum - value)
        ret += rootSum(node?.right, targetSum - value)
        return ret
        
    }









相关文章

网友评论

      本文标题:剑指 Offer II 050. 向下的路径节点之和

      本文链接:https://www.haomeiwen.com/subject/bhdnertx.html