class TN:
def __init__(self,value,left=None,right=None):
self.value = value
self.left = left
self.right = right
def list_to_tree(alist):
if alist == None:
return None
else:
return TN(alist[0],list_to_tree(alist[1]),list_to_tree(alist[2]))
def str_tree(atree,indent_char ='.',indent_delta=2):
def str_tree_1(indent,atree):
if atree == None:
return ''
else:
answer = ''
answer += str_tree_1(indent+indent_delta,atree.right)
answer += indent*indent_char+str(atree.value)+'\n'
answer += str_tree_1(indent+indent_delta,atree.left)
return answer
return str_tree_1(0,atree)
def count(t,value):
nodes = []
num = 0
nodes.append(t)
while len(nodes) > 0:
if nodes[0] == value:
num += 1
next = nodes.pop(0)
count(next,value)
return num
I need to write a recursive function count (other three functions cannot be changed); it is passed balanced binary tree and a value as arguments. It returns the number of times the values is in the tree. In the binary tree below, count(tree,1) returns 1, count(tree,2) returns 2, count(tree,3) returns 4
..1
....3
3
....3
..2
......2
....3
I called the following functions
tree = list_to_tree([3, [2, None, [3, None, None]], [1, [3, None, None], None]])
print('\nfor tree = \n',str_tree(tree))
for i in irange(1,3):
print('count(tree,'+str(i)+') = ', count(tree,i))
but it shows the error that "RecursionError: maximum recursion depth exceeded in comparison" can someone help me to fix the count function? Thanks in advance.