With the following recursive code to count leaf nodes of a binary tree, is there any way to make it faster or parallel-computing optimized in time?
Python code - (mag(P) = number of leaf nodes of tree P depth H, left(P) = produces left subtree and right(P)= produces right subtree, not given here, reduce the tree P to subtrees until terminal nodes are reached):
temp = 0
def mag(P):
global temp
if len(P) == 0: #counts the one terminal node
return temp+1
elif len(P) == 1: #counts the two terminal nodes
return temp+2
elif len(P) >= 2:
return mag(left(P)) + mag(right(P))