leetcode 404 Sum of Left Leaves

来源:互联网 发布:什么源码值得读知乎 编辑:程序博客网 时间:2024/05/29 16:16

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.

Subscribe to see which companies asked this question


# 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
        """
        return self.summiao(root)
    def summiao(self, root):
        if not root:
            return 0
        sum1=self.summiao(root.left)+self.summiao(root.right)
        if root.left!=None:
            if root.left.left==None and root.left.right==None:
                sum1=sum1+root.left.val
        return sum1

0 0
原创粉丝点击