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
class 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)
转载请注明原文地址: https://ju.6miu.com/read-17655.html