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


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. 向下的路径节点之和)