func pathSum(_ root: TreeNode?, _ sum: Int) -> Int {
if root == nil {
return 0
}
return helper(root, sum) + pathSum(root?.left, sum) + pathSum(root?.right, sum)
}
private func helper(_ node: TreeNode?, _ target: Int) -> Int {
if node == nil {
return 0
}
var result = 0
if node!.val == target {
result += 1
}
result += (helper(node?.left, target-node!.val) + helper(node?.right, target-node!.val))
return result
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme