V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
woostundy
V2EX  ›  Python

Python 求二叉树所有左叶节点的和

  •  
  •   woostundy · 2016-11-11 11:18:37 +08:00 · 3026 次点击
    这是一个创建于 2722 天前的主题,其中的信息可能已经有所发展或是发生改变。
    python
    
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if root is None or self.isleaf(root):
                return 0
            if self.isleaf(root.left):
                return root.left.val + self.sumOfLeftLeaves(root.right)
            else:
                return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
            
        def isleaf(self,root):
            return root.left is None and root.left is None
    

    原题地址是 https://leetcode.com/problems/sum-of-left-leaves/ 求解,这段代码哪里写错了?

    7 条回复    2016-11-11 18:40:35 +08:00
    billgreen1
        1
    billgreen1  
       2016-11-11 11:24:14 +08:00
    按我的理解, left leaves != left node

    ~~~python
    def is_leaf(self, node):
    return node is not None and node.left is None and node.right is None
    woostundy
        2
    woostundy  
    OP
       2016-11-11 11:36:06 +08:00
    @billgreen1 是的,求的是所有左叶节点的和。
    node is not None 的判断在最开始就做了。

    错误样例是
    [0,2,4,1,null,3,-1,5,1,null,6,null,8]
    算这个的时候错了
    zmrenwu
        3
    zmrenwu  
       2016-11-11 11:41:05 +08:00
    他不是要你算左叶子节点么?你的代码包含了非叶子节点在里面
    yonka
        4
    yonka  
       2016-11-11 11:52:21 +08:00   ❤️ 1
    return root.left is None and root.left is None

    看了好几遍不知道在干嘛。
    难道不是 return root is not None and root.left is None and root.right is None 吗?
    woostundy
        5
    woostundy  
    OP
       2016-11-11 11:56:04 +08:00
    @yonka 我擦,看出来了,把第二个自判断也写成 left 了。。
    晕,太马虎了
    woostundy
        6
    woostundy  
    OP
       2016-11-11 11:56:31 +08:00
    @billgreen1 是我发现写错了。多谢多谢
    doraemon1293
        7
    doraemon1293  
       2016-11-11 18:40:35 +08:00
    def isleaf(self,root):
    return root.left is None and root.left is None 不应该是 right 吗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1274 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 18:02 · PVG 02:02 · LAX 11:02 · JFK 14:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.