Sum of Left Leaves(递归和分治,dfs,树)
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.class Solution:
sum = 0
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.preOrder(root)
return self.sum
def preOrder(self, root):
if not root:
return
left = root.left
if left and not left.left and not left.right:
self.sum += left.val
self.preOrder(root.left)
self.preOrder(root.right)Last updated