LeetCode #404: Sum of Left Leaves

来源:互联网 发布:阿里云合作伙伴 logo 编辑:程序博客网 时间:2024/06/05 04:47

Problem Statement

(Source) Find the sum of all left leaves in a given binary tree.

Example:

    3   / \  9  20    /  \   15   7There 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 = Noneclass 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)
1 0
原创粉丝点击