编写一个代码满足一下要求1.输入字符序列,建立并输出一颗二叉树。 2.分别按先序、中序、后序遍历二叉树并输出遍历序列。 3.求二叉树的叶子结点个数。 4.给定元素序列a,b,c,d,e,f,g,h,j对应的权重集合{1,4,24,5,6,10,8,31,22,11},建立一棵哈夫曼树。 5.在主函数中设计- -个简单的菜单,分别调用. 上述算法。
时间: 2023-06-19 09:05:34 浏览: 104
好的,我可以为你编写这个代码。由于这个代码比较长,我先给出全部代码,再逐个解释。
```python
# 定义二叉树结构体
class BinaryTree:
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
# 建立二叉树
def create_binary_tree():
input_str = input("请输入二叉树的节点,以','分隔:")
node_list = input_str.split(',')
root = BinaryTree(node_list[0])
node_queue = [root]
front_index = 0
children_index = 1
while children_index < len(node_list):
left_value = node_list[children_index]
right_value = node_list[children_index+1] if children_index+1 < len(node_list) else None
parent = node_queue[front_index]
if left_value != '#':
left_child = BinaryTree(left_value)
parent.left = left_child
node_queue.append(left_child)
if right_value != '#':
right_child = BinaryTree(right_value)
parent.right = right_child
node_queue.append(right_child)
front_index += 1
children_index += 2
return root
# 先序遍历二叉树
def preorder_traversal(node, traversal_list):
if node is None:
return
traversal_list.append(node.value)
preorder_traversal(node.left, traversal_list)
preorder_traversal(node.right, traversal_list)
# 中序遍历二叉树
def inorder_traversal(node, traversal_list):
if node is None:
return
inorder_traversal(node.left, traversal_list)
traversal_list.append(node.value)
inorder_traversal(node.right, traversal_list)
# 后序遍历二叉树
def postorder_traversal(node, traversal_list):
if node is None:
return
postorder_traversal(node.left, traversal_list)
postorder_traversal(node.right, traversal_list)
traversal_list.append(node.value)
# 求二叉树的叶子节点个数
def count_leaf_node(node):
if node is None:
return 0
if node.left is None and node.right is None:
return 1
return count_leaf_node(node.left) + count_leaf_node(node.right)
# 建立哈夫曼树
def create_huffman_tree(elements, weights):
nodes = []
for i in range(len(elements)):
nodes.append(BinaryTree(elements[i]))
while len(nodes) > 1:
nodes.sort(key=lambda node: weights[elements.index(node.value)])
left_node = nodes.pop(0)
right_node = nodes.pop(0)
parent_node = BinaryTree(left_node.value + right_node.value)
parent_node.left = left_node
parent_node.right = right_node
nodes.append(parent_node)
return nodes[0]
# 主函数
if __name__ == '__main__':
while True:
print('请选择操作:')
print('1.建立并输出二叉树')
print('2.先序遍历二叉树')
print('3.中序遍历二叉树')
print('4.后序遍历二叉树')
print('5.求二叉树的叶子结点个数')
print('6.建立并输出哈夫曼树')
print('7.退出')
choice = input()
if choice == '1':
root = create_binary_tree()
print('二叉树建立成功!')
elif choice == '2':
traversal_list = []
preorder_traversal(root, traversal_list)
print('先序遍历结果为:', traversal_list)
elif choice == '3':
traversal_list = []
inorder_traversal(root, traversal_list)
print('中序遍历结果为:', traversal_list)
elif choice == '4':
traversal_list = []
postorder_traversal(root, traversal_list)
print('后序遍历结果为:', traversal_list)
elif choice == '5':
count = count_leaf_node(root)
print('叶子节点个数为:', count)
elif choice == '6':
elements = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j']
weights = [1, 4, 24, 5, 6, 10, 8, 31, 22, 11]
huffman_tree = create_huffman_tree(elements, weights)
print('哈夫曼树建立成功!')
elif choice == '7':
break
```
代码的实现分为以下几个部分:
1. 定义二叉树结构体
```python
class BinaryTree:
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
```
这里定义了一个二叉树节点的结构体,包括节点的值和指向左右节点的指针。
2. 建立二叉树
```python
def create_binary_tree():
input_str = input("请输入二叉树的节点,以','分隔:")
node_list = input_str.split(',')
root = BinaryTree(node_list[0])
node_queue = [root]
front_index = 0
children_index = 1
while children_index < len(node_list):
left_value = node_list[children_index]
right_value = node_list[children_index+1] if children_index+1 < len(node_list) else None
parent = node_queue[front_index]
if left_value != '#':
left_child = BinaryTree(left_value)
parent.left = left_child
node_queue.append(left_child)
if right_value != '#':
right_child = BinaryTree(right_value)
parent.right = right_child
node_queue.append(right_child)
front_index += 1
children_index += 2
return root
```
利用输入的字符序列建立二叉树,输入的字符序列格式为先序遍历的结果,其中'#'表示空节点。
3. 先序遍历二叉树
```python
def preorder_traversal(node, traversal_list):
if node is None:
return
traversal_list.append(node.value)
preorder_traversal(node.left, traversal_list)
preorder_traversal(node.right, traversal_list)
```
先序遍历二叉树,将遍历结果存入列表中。
4. 中序遍历二叉树
```python
def inorder_traversal(node, traversal_list):
if node is None:
return
inorder_traversal(node.left, traversal_list)
traversal_list.append(node.value)
inorder_traversal(node.right, traversal_list)
```
中序遍历二叉树,将遍历结果存入列表中。
5. 后序遍历二叉树
```python
def postorder_traversal(node, traversal_list):
if node is None:
return
postorder_traversal(node.left, traversal_list)
postorder_traversal(node.right, traversal_list)
traversal_list.append(node.value)
```
后序遍历二叉树,将遍历结果存入列表中。
6. 求二叉树的叶子节点个数
```python
def count_leaf_node(node):
if node is None:
return 0
if node.left is None and node.right is None:
return 1
return count_leaf_node(node.left) + count_leaf_node(node.right)
```
递归求解二叉树的叶子节点个数。
7. 建立哈夫曼树
```python
def create_huffman_tree(elements, weights):
nodes = []
for i in range(len(elements)):
nodes.append(BinaryTree(elements[i]))
while len(nodes) > 1:
nodes.sort(key=lambda node: weights[elements.index(node.value)])
left_node = nodes.pop(0)
right_node = nodes.pop(0)
parent_node = BinaryTree(left_node.value + right_node.value)
parent_node.left = left_node
parent_node.right = right_node
nodes.append(parent_node)
return nodes[0]
```
根据给定的元素序列和权重集合建立哈夫曼树。
8. 主函数
```python
if __name__ == '__main__':
while True:
print('请选择操作:')
print('1.建立并输出二叉树')
print('2.先序遍历二叉树')
print('3.中序遍历二叉树')
print('4.后序遍历二叉树')
print('5.求二叉树的叶子结点个数')
print('6.建立并输出哈夫曼树')
print('7.退出')
choice = input()
if choice == '1':
root = create_binary_tree()
print('二叉树建立成功!')
elif choice == '2':
traversal_list = []
preorder_traversal(root, traversal_list)
print('先序遍历结果为:', traversal_list)
elif choice == '3':
traversal_list = []
inorder_traversal(root, traversal_list)
print('中序遍历结果为:', traversal_list)
elif choice == '4':
traversal_list = []
postorder_traversal(root, traversal_list)
print('后序遍历结果为:', traversal_list)
elif choice == '5':
count = count_leaf_node(root)
print('叶子节点个数为:', count)
elif choice == '6':
elements = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j']
weights = [1, 4, 24, 5, 6, 10, 8, 31, 22, 11]
huffman_tree = create_huffman_tree(elements, weights)
print('哈夫曼树建立成功!')
elif choice == '7':
break
```
在主函数中设计一个简单的菜单,根据用户选择调用相应的函数。
阅读全文