70. The algorithm is simple and swift left and leaves it

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);
    }
}

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/93160020