初始化一个数据元素为字符串类型的二叉树,并对其实现创建及先序、中序、后序三种遍历
时间: 2024-02-02 22:05:09 浏览: 6
以下是 Python 代码实现:
```python
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, data):
node = Node(data)
if self.root is None:
self.root = node
else:
queue = []
queue.append(self.root)
while queue:
curr = queue.pop(0)
if curr.left is None:
curr.left = node
break
elif curr.right is None:
curr.right = node
break
else:
queue.append(curr.left)
queue.append(curr.right)
def preorder(self, node):
if node is not None:
print(node.data, end=' ')
self.preorder(node.left)
self.preorder(node.right)
def inorder(self, node):
if node is not None:
self.inorder(node.left)
print(node.data, end=' ')
self.inorder(node.right)
def postorder(self, node):
if node is not None:
self.postorder(node.left)
self.postorder(node.right)
print(node.data, end=' ')
# 创建二叉树
bt = BinaryTree()
bt.insert('A')
bt.insert('B')
bt.insert('C')
bt.insert('D')
bt.insert('E')
bt.insert('F')
bt.insert('G')
# 先序遍历
print('先序遍历:')
bt.preorder(bt.root)
print()
# 中序遍历
print('中序遍历:')
bt.inorder(bt.root)
print()
# 后序遍历
print('后序遍历:')
bt.postorder(bt.root)
print()
```
输出结果:
```
先序遍历:
A B D E C F G
中序遍历:
D B E A F C G
后序遍历:
D E B F G C A
```
阅读全文