码迷,mamicode.com
首页 > 其他好文 > 详细

404. Sum of Left Leaves

时间:2019-01-13 22:24:39      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:bsp   code   val   root   pen   最简   int   result   not   

题目来源:
 
自我感觉难度/真实难度:
 
题意:
 
分析:
 
自己的代码:
class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        left=[]
        if not root:
            return
        
            
        self.sumOfLeftLeaves(root.left)
        left.append(root.val)
        self.sumOfLeftLeaves(root.right)
        
        return sum(left)

 

代码效率/结果:
 
优秀代码:
class Solution:
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        result = 0
        if not root:
            return 0      
        if root.left and not root.left.left and not root.left.right:
            result += root.left.val
        return result+self.sumOfLeftLeaves(root.left)+self.sumOfLeftLeaves(root.right)   

 

代码效率/结果:
 36ms
自己优化后的代码:
 
反思改进策略:

1.树可以这样操作root.left.val

2.迭代要记住返回值是什么,想想最简单的情况

3.迭代可以出现在return中

 

404. Sum of Left Leaves

标签:bsp   code   val   root   pen   最简   int   result   not   

原文地址:https://www.cnblogs.com/captain-dl/p/10264184.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!