leetcood学习笔记-404-左叶子之和

题目描述:

方法一:递归

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        if not root:
            return 0
        if root.left and root.left.left == None and root.left.right == None:
            return root.left.val+self.sumOfLeftLeaves(root.right)
        else:
            return self.sumOfLeftLeaves(root.left)+self.sumOfLeftLeaves(root.right)

方法二:

def sumOfLeftLeaves(self, root: TreeNode) -> int:

    # n == 0 表示为左节点
    # n == 1 表示为右节点
    def sum(root, n):
        if root == None:
            return 0
        if root.left == None and root.right == None and n == 0:
            return root.val
        if root.left == None and root.right == None and n == 1:
            return 0

        return sum(root.left, 0) + sum(root.right, 1)
    # 如果只有一个根节点 return 0
    return sum(root, 1)

 

posted @ 2019-03-29 19:20  oldby  阅读(105)  评论(0编辑  收藏  举报