書籍タイトルをアルファベット順に出力する
この動画では、二分木に対するdepth first searchの走査を、in-order、pre-order、post-order の3通りで実装する方法を学びました。
次の二分探索木(binary search tree)には、いくつかの書籍タイトルが保存されています。

この木は bst 変数(15行目)にあらかじめ読み込まれています:
bst = CreateTree()
本のタイトルがアルファベット順に並ぶように、in-order 走査を適用できますか?
この演習はコースの一部です
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)