I have a tree and It is not a binary tree, so I want to compare all of the nodes and return the largest one, using recursion. I am having a problem of how to keep track of it, as I can’t put a global variable, as it has to be local… I guess… But then if the recursion goes it resets the local variable.
def tree_max(node):
max=1
if node.left == None and node.right == None:
if node.value>max:
max=node.value
return max
elif node.left == None and node.right != None:
return tree_max(node)
elif node.left != None and node.right == None:
return tree_max(node.left)
else:
return tree_max(node.left)
Any suggestions?
You don’t need to keep the maximum value in a variable across all recursive calls, and by all means, not a global one. In a well-structured recursion, the result will be passed around in the return value of each recursive call. Like this:
The above assumes that
nodeis notNone, ifnodecan be null then check for this condition before callingtree_max().