Q404 Sum of Left Leaves

2018-03-08  本文已影响12人  牛奶芝麻

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.
解题思路:
Python 实现:
# 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
        """
        if root == None:
            return 0
        if root.left != None and root.left.left == None and root.left.right == None:
            return root.left.val + self.sumOfLeftLeaves(root.right) # 左叶子加上在右子树中求左叶子之和
        return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) # 求左右子树中左叶子之和

上一篇 下一篇

猜你喜欢

热点阅读