Leetcode #404 Sum of Left Leaves

来源:互联网 发布:mac哪些好的软件下载 编辑:程序博客网 时间:2024/05/16 08:33

Description

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.

Explain

判断是否为左子树并且是否不存在子树,都满足则加上这个val
ps:才发现leetcode可以加参数= =

Code

# 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, isleft=False):        """        :type root: TreeNode        :rtype: int        """        if not root:            return 0        if not root.left and not root.right:            return root.val if isleft else 0        return self.sumOfLeftLeaves(root.left, True) + self.sumOfLeftLeaves(root.right, False)
0 0
原创粉丝点击