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

本文介绍了一种使用BFS算法解决二叉树中所有左叶子节点值的求和问题的方法。通过层序遍历,当遇到左子树且为叶子节点时,将该节点值累加至结果中。
781

被折叠的 条评论
为什么被折叠?



