首页 > 其他 > 详细

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

时间:2019-03-29 20:11:00      阅读:141      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

方法一:递归

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)

 

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

原文:https://www.cnblogs.com/oldby/p/10623397.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!