class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def inorder_to_postorder(expression):
root = Node(None)
current = root
for char in expression:
if char.isdigit():
node = Node(int(char))
current.left = node
current = node
else:
current.value = char
node = Node(None)
current.right = node
current = node
if current.left and current.right:
root = add_to_postorder(root)
current = root
return [node.value for node in postorder_traversal(root)]
def add_to_postorder(node):
if node.left and node.right:
node.left = add_to_postorder(node.left)
node.right = add_to_postorder(node.right)
return Node(node.right.value + node.left.value + node.value)
else:
return node
def postorder_traversal(node):
if node is None:
return []
return postorder_traversal(node.left) + postorder_traversal(node.right) + [node]
expression = "1+2*3"
print("中序表达式:", expression)
postfix_expression = inorder_to_postorder(expression)
print("后序表达式:", "".join(str(node.value) for node in postfix_expression))