博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode: Python]404. Sum of Left Leaves
阅读量:3557 次
发布时间:2019-05-20

本文共 1506 字,大约阅读时间需要 5 分钟。

Title:

Find the sum of all left leaves in a given binary tree.

Example:

3   / \  9  20    /  \   15   7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

方法一:42ms

递归

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def isLeaf(self, root):        if root.left == None and root.right == None:            return True    def sumOfLeftLeaves(self, root):        """        :type root: TreeNode        :rtype: int        """        if root == None:            return 0        s = 0        if root.left and self.isLeaf(root.left):            s += root.left.val        return s + self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

方法二:38ms

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def sumOfLeftLeaves(self, root):        """        :type root: TreeNode        :rtype: int        """        self.ans = 0         def findleave(node):             if not node:                 return 0             if node.left:                 if not node.left.left and not node.left.right:                     self.ans += node.left.val                else:                    findleave(node.left)             if node.right:                 findleave(node.right)        findleave(root)

转载地址:http://igcrj.baihongyu.com/

你可能感兴趣的文章
js对象的深拷贝,你真的觉得很简单吗?
查看>>
你真的了解map方法吗?手动实现数组map方法。
查看>>
带你手动实现call方法,让你收获满满
查看>>
前端知识体系
查看>>
使用join查询方式找出没有分类的电影id以及名称
查看>>
Qt教程(2) : Qt元对象系统
查看>>
驱动开发误用指针错误:Unable to handle kernel NULL pointer dereference at virtual address
查看>>
Linux部署DocSystem知识/文件管理系统
查看>>
Centos7开机自启动脚本无法使用备用方案
查看>>
jvm虚拟机内存详解
查看>>
线程的创建方式
查看>>
DNS是什么
查看>>
Hbase架构
查看>>
PaddleX的C++使用
查看>>
MyBatis-Plus代码生成器
查看>>
我的第一个SpringBoot项目(一)
查看>>
回文数
查看>>
伪背包问题!
查看>>
求10000以内n的阶乘!
查看>>
static关键字
查看>>