剑指 Offer II 050. 向下的路径节点之和
2022-06-30 本文已影响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
}