【发布时间】:2015-08-22 20:50:28
【问题描述】:
我正在尝试编写代码来打印二叉树中的路径,该路径加起来就是传递给函数的总和。对于一个简单的测试用例,以下代码一直失败:
最后执行的输入:Binary Tree = [1], sum = 1
运行时错误消息:
Line 26: TypeError: object of type 'NoneType' has no len()
标准输出:None None
我无法理解leftPath 和rightPath 是如何变成None 的。我根本不返回 None。
'''
Created on Aug 12, 2015
@author: debpriyas
'''
class BTNode(object):
'''
classdocs
'''
def __init__(self,value, leftBTNode=None, rightBTNode=None):
'''
Constructor
'''
self.value = value
self.left = leftBTNode
self.right = rightBTNode
# To deal with duplicate values in BST.
self.count = 1
def pathSum(root, sum):
return pathSumHelper( root, sum, [])
def pathSumHelper(root, sum, path):
if root == None:
if sum == 0:
return path
else:
return []
leftPath = pathSumHelper(root.left, sum-root.value, path.append(root.value))
rightPath = pathSumHelper(root.right, sum-root.value, path.append(root.value))
print leftPath, rightPath
if len(leftPath) == 0 and len(rightPath) == 0:
return []
if len(leftPath) == 0:
return [rightPath]
elif len(rightPath) == 0:
return [leftPath]
return [leftPath, rightPath]
if __name__ == '__main__':
root = BTNode(1)
print pathSum(root, 1)
【问题讨论】:
-
请尝试将您截取的代码转换为minimal, complete, and verifiable example。
-
@das-g:更改的代码可以在隔离系统上运行。代码是最小的并且更早完成。现在我猜它是可以验证的。
标签: list function python-2.7 append