404. 左叶子之和

"""
404. 左叶子之和
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
"""
class Solution(object):
def sumOfLeftLeaves(self, root):
def bfs(root1):
ans = 0
if not root1: return
if root1.left:
ans += root1.left.val if self.isLeaves(root1.left) else bfs(root1.left)
if root1.right and not self.isLeaves(root1.right):
ans += bfs(root1.right)
return ans
return bfs(root)


def isLeaves(self, root):
if not root.left and not root.right:
return True
else:
return False

class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None

if __name__ == "__main__":
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
res = Solution().sumOfLeftLeaves(root)
print(res)

posted on 2021-12-13 10:04  random_boy  阅读(15)  评论(0)    收藏  举报

导航