開始使用免費開始

依字母順序列印書名

這支影片介紹了把深度優先搜尋(DFS)應用到二元樹的三種走訪方式:中序(in-order)、先序(pre-order)、後序(post-order)。

在下列的二元搜尋樹(BST)中,已經儲存了一些書名。

Graphical representation of a binary search tree.

這棵樹已預先載入在變數 bst(第 15 行):

bst = CreateTree()

你可以套用中序走訪,讓書名依字母順序顯示嗎?

本練習屬於課程

Data Structures and Algorithms in 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)
編輯並執行程式碼