404. Sum of Left Leaves (Easy)

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.检查当前节点的左子节点是否是左子叶;
2.若是叶子节点,则返回左子叶的值加上对当前结点的右子节点调用递归的结果;
3.若不是叶子结点,我们对左右子节点分别调用递归函数,返回二者之和;

# Definition for a binary tree node.
# class TreeNode():
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution():
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        ans = 0
        l, r = root.left, root.right
        if root:
            if l and (l.left or l.right) is None:
                ans += l.val
            ans += self.sumOfLeftLeaves(l) + self.sumOfLeftLeaves(r)
        return ans
原文地址:https://www.cnblogs.com/yancea/p/7512852.html