本のタイトルをアルファベット順に出力する
このビデオでは、二分木に対して深さ優先探索を実装する3つの方法、すなわち通りがけ順(in-order)、行きがけ順(pre-order)、帰りがけ順(post-order)を学びました。
以下の二分探索木には、本のタイトルが格納されています。

このツリーはbst変数(15行目)にあらかじめ読み込まれています。
bst = CreateTree()
通りがけ順走査(in-order traversal)を適用して、本のタイトルをアルファベット順に表示してみましょう。
この演習はコースの一部です
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)