Left to calculate all the leaves of the binary tree and set.
Example:
3
/ \
9 20
/ \
15 7
In this binary tree, there are two left leaves, respectively 9 and 15, it returns 24
solution:
/**
* 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 {
guard root != nil else {
return 0
}
if (((root?.left) != nil) && root?.left!.left == nil && root!.left!.right == nil){
return root!.left!.val + sumOfLeftLeaves(root!.right);
}
return sumOfLeftLeaves(root!.left)+sumOfLeftLeaves(root!.right);
}
}