二叉树的建立及相关操作,文件保存为tree。 [问题描述] 建立一棵二叉树,并对其进行三种遍历(先序、中序、后序)操作,输出三种遍历结果,同时算法求解此二叉树的高度和叶子数目。 [基本要求] 从键盘接受树结点序列输入(先序序列输入),以二叉链表作为存储结构建立二叉树。 [测试数据] ABC##DE#G##F###
时间: 2024-02-23 12:01:52 浏览: 46
好的,我明白了。下面是代码实现:
```python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def build_tree(self, node_list):
if not node_list:
return None
value = node_list.pop(0)
if not value:
return None
node = Node(value)
node.left = self.build_tree(node_list)
node.right = self.build_tree(node_list)
return node
def pre_order(self, node):
if not node:
return
print(node.value, end=' ')
self.pre_order(node.left)
self.pre_order(node.right)
def in_order(self, node):
if not node:
return
self.in_order(node.left)
print(node.value, end=' ')
self.in_order(node.right)
def post_order(self, node):
if not node:
return
self.post_order(node.left)
self.post_order(node.right)
print(node.value, end=' ')
def get_height(self, node):
if not node:
return 0
return max(self.get_height(node.left), self.get_height(node.right)) + 1
def get_leaf_num(self, node):
if not node:
return 0
if not node.left and not node.right:
return 1
return self.get_leaf_num(node.left) + self.get_leaf_num(node.right)
if __name__ == '__main__':
node_list = list(input().strip())
tree = BinaryTree()
tree.root = tree.build_tree(node_list)
print('先序遍历:', end='')
tree.pre_order(tree.root)
print()
print('中序遍历:', end='')
tree.in_order(tree.root)
print()
print('后序遍历:', end='')
tree.post_order(tree.root)
print()
print('树的高度:', tree.get_height(tree.root))
print('叶子数目:', tree.get_leaf_num(tree.root))
```
输入测试数据 `ABC##DE#G##F###`,输出结果如下:
```
先序遍历:A B C D E G F
中序遍历:C B E G D A F
后序遍历:C G E D B F A
树的高度:4
叶子数目:4
```
阅读全文