生成代码 首先,从记事本中依次读取每一行通讯录内容,将读取的所有教师信息按照年龄构建成二叉排序树,如图8-2所示。然后,分别通过对二叉排序树的先序遍历显示所有教师信息,通过二叉排序树的后序遍历按照姓名查询某位教师通讯信息,通过二叉排序树后序遍历按照部门查询该部门所有教师的通讯信息;最后,通过二叉排序树的中序遍历输出青年教师(≤35岁)通讯信息,遍历过程中,如果某个结点的年龄大于35岁,那么不再需要遍历该结点的右子树。
时间: 2024-02-21 09:01:11 浏览: 70
C#开发的手机通讯录批量导入工具源代码
以下是可能的代码实现,仅供参考:
```python
class Teacher:
def __init__(self, name, age, department, phone):
self.name = name
self.age = age
self.department = department
self.phone = phone
class TreeNode:
def __init__(self, teacher):
self.teacher = teacher
self.left = None
self.right = None
class TeacherBST:
def __init__(self):
self.root = None
def insert(self, teacher):
new_node = TreeNode(teacher)
if self.root is None:
self.root = new_node
else:
current = self.root
while current is not None:
if teacher.age < current.teacher.age:
if current.left is None:
current.left = new_node
break
current = current.left
else:
if current.right is None:
current.right = new_node
break
current = current.right
def preorder_traversal(self, node=None):
if node is None:
node = self.root
if node is not None:
print(node.teacher.name, node.teacher.age, node.teacher.department, node.teacher.phone)
self.preorder_traversal(node.left)
self.preorder_traversal(node.right)
def postorder_traversal_name(self, node=None, name=None):
if node is None:
node = self.root
if node is not None:
self.postorder_traversal_name(node.left, name)
self.postorder_traversal_name(node.right, name)
if node.teacher.name == name:
print(node.teacher.name, node.teacher.age, node.teacher.department, node.teacher.phone)
def postorder_traversal_department(self, node=None, department=None):
if node is None:
node = self.root
if node is not None:
self.postorder_traversal_department(node.left, department)
self.postorder_traversal_department(node.right, department)
if node.teacher.department == department:
print(node.teacher.name, node.teacher.age, node.teacher.department, node.teacher.phone)
def inorder_traversal_young(self, node=None):
if node is None:
node = self.root
if node is not None:
self.inorder_traversal_young(node.left)
if node.teacher.age <= 35:
print(node.teacher.name, node.teacher.age, node.teacher.department, node.teacher.phone)
if node.teacher.age < 35:
self.inorder_traversal_young(node.right)
```
在上面的代码中,`Teacher`类表示一个教师的信息,`TreeNode`类表示二叉排序树中的一个结点,`TeacherBST`类表示二叉排序树。该类具有以下方法:
- `insert(teacher)`:将一个教师的信息插入到二叉排序树中。
- `preorder_traversal(node=None)`:先序遍历二叉排序树,并输出每个结点的教师信息。如果不传入参数`node`,则默认从根节点开始遍历。
- `postorder_traversal_name(node=None, name=None)`:后序遍历二叉排序树,并根据姓名查询某个教师的通讯信息。如果不传入参数`node`,则默认从根节点开始遍历。如果不传入参数`name`,则不会输出任何信息。
- `postorder_traversal_department(node=None, department=None)`:后序遍历二叉排序树,并根据部门查询该部门所有教师的通讯信息。如果不传入参数`node`,则默认从根节点开始遍历。如果不传入参数`department`,则不会输出任何信息。
- `inorder_traversal_young(node=None)`:中序遍历二叉排序树,并输出所有年龄小于等于35岁的教师的通讯信息。如果不传入参数`node`,则默认从根节点开始遍历。如果某个结点的年龄大于35岁,那么不会遍历该结点的右子树。
你可以根据上面的代码编写你自己的程序,并根据自己的需要进行修改。
阅读全文