按字母顺序打印书名
本视频向您展示了在二叉树中实现深度优先搜索的三种遍历方式:中序遍历、先序遍历和后序遍历。
在下面的二叉搜索树中,存储了一些书籍的标题。

该树已在变量 bst(第 15 行)中预加载:
bst = CreateTree()
您能应用中序遍历,让这些书名按字母顺序输出吗?
本练习是课程的一部分
Python 中的数据结构与算法
练习说明
- 检查
current_node是否存在。 - 在树的相应一侧递归调用
in_order()函数。 - 打印
current_node的值。 - 在树的另一侧递归调用
in_order()函数。
交互式实操练习
通过完成这段示例代码来试试这个练习。
class BinarySearchTree:
def __init__(self):
self.root = None
def in_order(self, current_node):
# Check if current_node exists
if ____:
# Call recursively with the appropriate half of the tree
self.in_order(current_node.____)
# Print the value of the current_node
print(____)
# Call recursively with the appropriate half of the tree
self.in_order(current_node.____)
bst = CreateTree()
bst.in_order(bst.root)