题目描述:
LeetCode 404. Sum of Left Leaves
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.
题目大意:
给定二叉树,计算其所有左叶子的和。
解题思路:
遍历二叉树
Python代码:
# 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 sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
ans = 0
if root:
l, r = root.left, root.right
if l and (l.left or l.right) is None:
ans += l.val
ans += self.sumOfLeftLeaves(l) + self.sumOfLeftLeaves(r)
return ans
本文链接:http://bookshadow.com/weblog/2016/09/25/leetcode-sum-of-left-leaves/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。