Find the sum of all left leaves in a given binary tree.
Example:
1 2 3 4 5 6 7 8
3 / \ 9 20 / \ 15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
思路
Recursion.
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution: defsumOfLeftLeaves(self, root: TreeNode) -> int: if root isNone: return0 res = self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) if root.left and root.left.left isNoneand root.left.right isNone: res += root.left.val return res