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.
这道题比较简单,不过感觉说的不是很清楚,只是求所有左叶子节点的和。
用bfs算法,层序遍历。
如果这个节点是左子树,而且是叶子节点,则把和相加。
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if root is None:return 0
bfs=[root]
res=0
while bfs:
temp=[]
for node in bfs:
if node.left:
temp.append(node.left)
if (node.left.left or node.left.right) is None:
res+=node.left.val
if node.right:temp.append(node.right)
bfs=temp
return res