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)

浙公网安备 33010602011771号