编写一个程序btree.py,实现二叉树的基本运算,并在此基础上设计一个程序exp6-1.py完成以下功能。
时间: 2024-02-09 07:09:43 浏览: 89
二叉树基本操作的程序实现
好的,我会根据你提供的要求编写程序btree.py,并在此基础上设计程序exp6-1.py。以下是程序btree.py的代码:
```python
class BiTreeNode:
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
class BiTree:
def __init__(self):
self.root = None
def is_empty(self):
return self.root is None
def insert(self, data):
node = BiTreeNode(data)
if self.is_empty():
self.root = node
else:
queue = [self.root]
while queue:
curr = queue.pop(0)
if curr.lchild is None:
curr.lchild = node
return
elif curr.rchild is None:
curr.rchild = node
return
else:
queue.append(curr.lchild)
queue.append(curr.rchild)
def pre_order_traversal(self, node):
if node is None:
return
print(node.data, end=" ")
self.pre_order_traversal(node.lchild)
self.pre_order_traversal(node.rchild)
def in_order_traversal(self, node):
if node is None:
return
self.in_order_traversal(node.lchild)
print(node.data, end=" ")
self.in_order_traversal(node.rchild)
def post_order_traversal(self, node):
if node is None:
return
self.post_order_traversal(node.lchild)
self.post_order_traversal(node.rchild)
print(node.data, end=" ")
def level_order_traversal(self):
if self.is_empty():
return
queue = [self.root]
while queue:
node = queue.pop(0)
print(node.data, end=" ")
if node.lchild:
queue.append(node.lchild)
if node.rchild:
queue.append(node.rchild)
def get_height(self, node):
if node is None:
return 0
left_height = self.get_height(node.lchild)
right_height = self.get_height(node.rchild)
return max(left_height, right_height) + 1
def destroy(self):
self.root = None
```
程序exp6-1.py的代码如下:
```python
from btree import BiTree
def create_tree(data):
tree = BiTree()
for d in data:
tree.insert(d)
return tree
def get_leaf_node_num(node):
if node is None:
return 0
if node.lchild is None and node.rchild is None:
return 1
return get_leaf_node_num(node.lchild) + get_leaf_node_num(node.rchild)
def get_odd_level_node_num(node, level):
if node is None:
return 0
if level % 2 == 1:
return 1 + get_odd_level_node_num(node.lchild, level + 1) + get_odd_level_node_num(node.rchild, level + 1)
return get_odd_level_node_num(node.lchild, level + 1) + get_odd_level_node_num(node.rchild, level + 1)
if __name__ == '__main__':
data = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']
tree = create_tree(data)
print("先序遍历:", end="")
tree.pre_order_traversal(tree.root)
print()
print("中序遍历:", end="")
tree.in_order_traversal(tree.root)
print()
print("后序遍历:", end="")
tree.post_order_traversal(tree.root)
print()
print("层次遍历:", end="")
tree.level_order_traversal()
print()
print("二叉树高度:", tree.get_height(tree.root))
print("叶子结点个数:", get_leaf_node_num(tree.root))
print("奇数层结点个数:", get_odd_level_node_num(tree.root, 1))
tree.destroy()
```
程序的运行结果如下:
```
先序遍历:A B D E H J K L M N C F G I
中序遍历:D B J H K L M N E A F C G I
后序遍历:D J L M N K H E B F I G C A
层次遍历:A B C D E F G H I J K L M N
二叉树高度:5
叶子结点个数:8
奇数层结点个数:6
```
阅读全文