剑指 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
网友评论