leetcode之Sum of Left Leaves(404)

题目:

计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

python代码:

class Solution:
    def sumOfLeftLeaves(self, root):
        return self.dfs(root,False)
    
    def dfs(self,root,isLeft):
        
        if root == None:
            return 0
        if root.left == None and root.right == None and isLeft == True:
            return root.val
        return self.dfs(root.left,True) + self.dfs(root.right,False) 

猜你喜欢

转载自blog.csdn.net/cuicheng01/article/details/81409285