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.


1
class Solution(object): 2 def sumOfLeftLeaves(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: int 6 """ 7 ans = [] 8 if not root: 9 return 0 10 self.sumLeft(root, ans) 11 return sum(ans) 12 13 def sumLeft(self, node, ans): 14 if node.left is not None: 15 if node.left.right is None and node.left.left is None: 16 ans.append(node.left.val) 17 else: 18 self.sumLeft(node.left, ans) 19 20 if node.right != None: 21 self.sumLeft(node.right, ans)

注意: 如果想在辅助函数里维护一个变量为sum of left leaves。这个变量需要是一个全局变量。

 

可以用如下似乎递归求解。

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        elif root.left and not root.left.left and not root.left.right:
            return root.left.val + self.sumOfLeftLeaves(root.right)
        else:
            return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

 

posted @ 2016-12-27 10:13  lettuan  阅读(127)  评论(0)    收藏  举报