在二元搜尋樹中插入節點
在影片中,你已經學到什麼是二元搜尋樹(BST),以及如何實作它的主要操作。
在這個練習中,你將實作一個函式,把節點插入 BST。
為了測試你的程式碼,你可以使用下列這棵樹:

節點包含書名,並依字母順序構成 BST。
這棵樹已預先載入到變數 bst:
bst = CreateTree()
你可以用以下程式碼檢查節點是否正確插入:
bst.insert("Pride and Prejudice")
print(search(bst, "Pride and Prejudice"))
本練習屬於課程
Data Structures and Algorithms in Python
練習說明
- 檢查 BST 是否為空。
- 檢查要插入的資料是否小於目前節點的資料。
- 檢查要插入的資料是否大於目前節點的資料。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, data):
new_node = TreeNode(data)
# Check if the BST is empty
if ____ == None:
self.root = new_node
return
else:
current_node = self.root
while True:
# Check if the data to insert is smaller than the current node's data
if ____ < ____:
if current_node.left_child == None:
current_node.left_child = new_node
return
else:
current_node = current_node.left_child
# Check if the data to insert is greater than the current node's data
elif ____ > ____:
if current_node.right_child == None:
current_node.right_child = new_node
return
else:
current_node = current_node.right_child
bst = CreateTree()
bst.insert("Pride and Prejudice")
print(search(bst, "Pride and Prejudice"))