算法: Sum of left Leaves

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)
    }
}
    原文作者:TimberTang
    原文地址: https://www.jianshu.com/p/493e5829bce2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞