404. Sum of Left Leaves

Posted boluo007

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
# 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
        """
        if root is None:
            return 0
        self.num = 0
        self.helper(root,0)
        return self.num
    
    def helper(self, root, left):
        if root.left is None and root.right is None and left == 1:
            self.num += root.val
        
        if root.left:
            self.helper(root.left, 1)
        if root.right:
            self.helper(root.right, 0)
            
            
        

 

以上是关于404. Sum of Left Leaves的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-404. Sum of Left Leaves

404. Sum of Left Leaves

Leetcode 404. Sum of Left Leaves

404. Sum of Left Leaves

404. Sum of Left Leaves

404. Sum of Left Leaves