美文网首页Swift LeetCode
算法: Sum of left Leaves

算法: Sum of left Leaves

作者: TimberTang | 来源:发表于2018-04-17 11:19 被阅读12次

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

相关文章

网友评论

    本文标题:算法: Sum of left Leaves

    本文链接:https://www.haomeiwen.com/subject/lneukftx.html