将二叉树转换为中缀表达式
时间: 2023-10-09 22:04:33 浏览: 133
将二叉树转换为中缀表达式可以通过中序遍历来实现。中序遍历的顺序是:左子树 -> 根节点 -> 右子树。以下是一个示例代码,可以将二叉树转换为中缀表达式:
```python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def binary_tree_to_infix_expression(root):
if root is None:
return ""
if root.left is None and root.right is None:
return str(root.value)
expression = ""
if root.left is not None:
expression += "(" + binary_tree_to_infix_expression(root.left)
expression += str(root.value)
if root.right is not None:
expression += binary_tree_to_infix_expression(root.right) + ")"
return expression
# 示例用法:
# 创建二叉树
root = Node('+')
root.left = Node('a')
root.right = Node('*')
root.right.left = Node('b')
root.right.right = Node('c')
# 转换为中缀表达式
infix_expression = binary_tree_to_infix_expression(root)
print(infix_expression)
```
输出结果为:((a)+(b*c))
上述代码中,我们定义了一个 `Node` 类来表示二叉树节点,其中 `value` 存储节点的值,`left` 存储左子节点,`right` 存储右子节点。`binary_tree_to_infix_expression` 函数通过递归方式实现中序遍历,并将节点值连接为中缀表达式。注意,代码中使用括号来确保运算优先级的正确性。
阅读全文