假设我有一个树,其中内部节点是浮点值的操作,叶节点是浮点终端。现在,我想遍历这个树并获得结果函数。一种方法可能是这样做:
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
这个问题是每次需要大量调用Python中的函数具体来说,有没有办法可以将这个树转换成可以在函数中运行的Python语句列表?