開始使用免費開始

修正樹狀結構實作中的臭蟲

你拿到了一個應該要建立下列二元樹的程式:

Graphical representation of a tree.

測試後你發現程式有誤。你可以把它修好,讓它正確運作嗎?

本練習屬於課程

Data Structures and Algorithms in Python

檢視課程

練習說明

  • 修正 init() 方法中的錯誤。
  • 修正建立 root_node 時的錯誤。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

class TreeNode:
  
  def __init__(self, data, left=None, right=None):
    # Correct the mistakes
    self.data = None
    self.left_child = None
    self.right_child = None

node1 = TreeNode("B")
node2 = TreeNode("C")
# Correct the mistake
root_node = TreeNode(node1, node2, "A")
編輯並執行程式碼