zoukankan      html  css  js  c++  java
  • 404. Sum of Left Leaves

    题目来源:
     
    自我感觉难度/真实难度:
     
    题意:
     
    分析:
     
    自己的代码:
    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中

  • 相关阅读:
    FreeSql 教程引导
    Day3-JS-JavaScript 函数专题
    Day2-JS-JSON
    Day2-JS-let和const
    Day2-JS-this 关键字
    Day2-JS-JavaScript 验证 API
    Day2-JS-表单
    Day2-JS-严格模式
    Day2-JS-JavaScript 错误
    Day2-JS-正则表达式
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10264184.html
Copyright © 2011-2022 走看看