Problem Statement
(Source) 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.
Solution
这道题有很明显的递归结构。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self, root):
if not root:
return 0
elif not root.left and not root.right:
return root.val
else:
return self.sumOfLeftLeaves(root)
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
else:
return self.helper(root.left) + self.sumOfLeftLeaves(root.right)