您的位置:首页 > 其它

LeetCode #404: Sum of Left Leaves

2016-10-13 23:25 447 查看

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  递归