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/ 求解,这段代码哪里写错了?
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 |
![]() | 2 woostundy OP @billgreen1 是的,求的是所有左叶节点的和。 node is not None 的判断在最开始就做了。 错误样例是 [0,2,4,1,null,3,-1,5,1,null,6,null,8] 算这个的时候错了 |
![]() | 3 zmrenwu 2016-11-11 11:41:05 +08:00 他不是要你算左叶子节点么?你的代码包含了非叶子节点在里面 |
4 yonka 2016-11-11 11:52:21 +08:00 ![]() 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 吗? |
![]() | 6 woostundy OP @billgreen1 是我发现写错了。多谢多谢 |
![]() | 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 吗 |