根据我所问的上一个问题生成的代码,以菜单形式完成下面几个的输出:1.打印二叉树的构造过程;2.打印公式的后缀形式;3.二叉树的后序遍历序列;4.输入每个变量的值,计算并显示公式的真值,打印二叉树的评估过程;5.显示公式的真值表
时间: 2024-03-25 07:37:20 浏览: 62
输入后缀表达式,即时生成对应的二叉树,计算出表达式的值,并且输出对应的前缀表达式、中缀表达式
好的,根据您的需求,我来为您完成相应的代码:
1. 打印二叉树的构造过程
```python
class Node:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
def build_tree(expression):
stack = []
for char in expression:
if char.isalpha():
node = Node(char)
stack.append(node)
else:
node = Node(char)
node.right = stack.pop()
node.left = stack.pop()
stack.append(node)
return stack.pop()
def print_tree(node, level=0):
if node:
print(' ' * level + str(node.val))
print_tree(node.left, level + 1)
print_tree(node.right, level + 1)
```
2. 打印公式的后缀形式
```python
def infix_to_postfix(expression):
stack = []
postfix_list = []
precedence = {'(': 0, 'or': 1, 'and': 2, 'not': 3}
for char in expression:
if char.isalpha():
postfix_list.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
top_token = stack.pop()
while top_token != '(':
postfix_list.append(top_token)
top_token = stack.pop()
else:
while stack and precedence[stack[-1]] >= precedence[char]:
postfix_list.append(stack.pop())
stack.append(char)
while stack:
postfix_list.append(stack.pop())
return " ".join(postfix_list)
```
3. 二叉树的后序遍历序列
```python
def postorder_traversal(node):
if node:
postorder_traversal(node.left)
postorder_traversal(node.right)
print(node.val, end=' ')
```
4. 输入每个变量的值,计算并显示公式的真值,打印二叉树的评估过程
```python
def evaluate(node, var_dict):
if node.val.isalpha():
return var_dict.get(node.val)
else:
if node.val == 'not':
return not evaluate(node.right, var_dict)
elif node.val == 'and':
return evaluate(node.left, var_dict) and evaluate(node.right, var_dict)
elif node.val == 'or':
return evaluate(node.left, var_dict) or evaluate(node.right, var_dict)
def evaluate_expression(expression):
tree = build_tree(expression)
var_dict = {}
for var in set([char for char in expression if char.isalpha()]):
value = input(f"Enter the value for {var}: ")
var_dict[var] = bool(int(value))
print_tree(tree)
result = evaluate(tree, var_dict)
print(f"The result is: {result}")
```
5. 显示公式的真值表
```python
def generate_truth_table(expression):
variables = sorted(set([char for char in expression if char.isalpha()]))
print(" ".join(variables) + " | Result")
print("-" * (len(variables) * 2 + 8))
for i in range(2 ** len(variables)):
var_dict = {}
binary = bin(i)[2:].zfill(len(variables))
for j, var in enumerate(variables):
var_dict[var] = bool(int(binary[j]))
result = evaluate(build_tree(expression), var_dict)
print(" ".join(binary) + f" | {int(result)}")
```
以上就是根据您的需求所提供的代码,希望能够帮到您!
阅读全文