Suppose I have a tree where internal nodes are operations on floating-point values and leaf nodes are floating-point terminals. Now, I want to traverse this tree and get the resulting function. One way might be to do this:
def Execute(tree):
result = 0
symbol = tree.data
if (symbol in {'/', '*', '+', '-'}):
if (symbol == '/'):
result = Execute(tree.left) / Execute(tree.right)
elif (symbol == '*'):
result = Execute(tree.left) * Execute(tree.right)
elif (symbol == '+'):
result = Execute(tree.left) + Execute(tree.right)
elif (symbol == '-'):
result = Execute(tree.left) - Execute(tree.right)
else:
return tree.data
return result
The problem with this is that it would require a lot of calls to a function in Python every time Specifically, is there a way I could convert this tree to a list of Python statements that could be run in a function?