404. Sum of Left Leaves

来源:互联网 发布:魏晨全球歌迷会淘宝网 编辑:程序博客网 时间:2024/06/16 18:03

Find the sum of all left leaves in a given binary tree.

Example:

    3   / \  9  20    /  \   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def sumOfLeftLeaves(self, root):        """        :type root: TreeNode        :rtype: int        """        sum=0        if(root):            l,r=root.left,root.right            if l and (l.left or l.right) is None:                sum+=l.val            sum=self.sumOfLeftLeaves(l)+sum+self.sumOfLeftLeaves(r)        return sum        

0 0
原创粉丝点击