用python语言编写使用栈和二叉树对中辍表达式求值的程序
时间: 2023-06-24 13:08:23 浏览: 100
可以按照以下步骤实现:
1. 定义一个栈类,包括初始化方法、压栈方法、出栈方法和查看栈顶元素方法。
2. 定义一个二叉树类,包括初始化方法、插入节点方法和求值方法。
3. 将中缀表达式转换为后缀表达式。
4. 遍历后缀表达式,如果是数字则压入栈中,如果是运算符则弹出栈顶的两个数字进行计算,然后再将结果压入栈中。
5. 最后栈中只剩下一个元素,即为表达式的值。
下面是代码实现:
```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, val):
node = Node(val)
if self.root is None:
self.root = node
else:
current = self.root
while True:
if val < current.val:
if current.left is None:
current.left = node
break
else:
current = current.left
else:
if current.right is None:
current.right = node
break
else:
current = current.right
def evaluate(self, node):
if node.left is None and node.right is None:
return int(node.val)
else:
left_val = self.evaluate(node.left)
right_val = self.evaluate(node.right)
if node.val == '+':
return left_val + right_val
elif node.val == '-':
return left_val - right_val
elif node.val == '*':
return left_val * right_val
elif node.val == '/':
return left_val / right_val
def infix_to_postfix(infix):
postfix = ''
stack = Stack()
precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
for token in infix:
if token.isdigit():
postfix += token + ' '
elif token in '+-*/':
while not stack.is_empty() and precedence[stack.peek()] >= precedence[token]:
postfix += stack.pop() + ' '
stack.push(token)
elif token == '(':
stack.push(token)
elif token == ')':
while stack.peek() != '(':
postfix += stack.pop() + ' '
stack.pop()
while not stack.is_empty():
postfix += stack.pop() + ' '
return postfix.strip()
def postfix_evaluation(postfix):
stack = Stack()
for token in postfix.split():
if token.isdigit():
stack.push(token)
else:
right = int(stack.pop())
left = int(stack.pop())
if token == '+':
stack.push(left + right)
elif token == '-':
stack.push(left - right)
elif token == '*':
stack.push(left * right)
elif token == '/':
stack.push(left / right)
return int(stack.pop())
if __name__ == '__main__':
infix_expression = input('请输入中缀表达式:')
postfix_expression = infix_to_postfix(infix_expression)
print('后缀表达式为:', postfix_expression)
binary_tree = BinaryTree()
for token in postfix_expression.split():
binary_tree.insert(token)
result = binary_tree.evaluate(binary_tree.root)
print('表达式的值为:', result)
```
这个程序可以让用户输入中缀表达式,将其转换为后缀表达式,并使用二叉树求值。
阅读全文