Sum of left Leaves
计算二叉树种所有叶子左叶子节点的值的总合
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func sumOfLeftLeaves(_ root: TreeNode?) -> Int {
var ans = 0
guard let ro = root else { return 0 }
if ro.left != nil && ro.left?.left == nil && ro.left?.right == nil {
ans = ans + (ro.left?.val)!
}
return ans + sumOfLeftLeaves(ro.left) + sumOfLeftLeaves(ro.right)
}
}