I am trying to write a code to print the path in a Binary Tree which add up to the sum passed to the function. To which the below code keeps on failing for a simple test case:
Last executed input: Binary Tree = [1], sum = 1
Runtime Error Message:
Line 26: TypeError: object of type 'NoneType' has no len()
Stdout:None None
I cannot understand how the leftPath and rightPath are becoming None. I am not returning None at all.
'''
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)