簡體   English   中英

為什么下面的代碼會拋出錯誤?

[英]Why is the following code throwing an error?

所以,我試圖定義一個 function 來反轉二叉樹,當我運行下面的代碼,然后執行a_node.binInversion()時,我收到錯誤消息,“NameError: name 'binInversion' is not defined ”。 為什么會發生這種錯誤?

我正在執行的代碼如下:

class BinaryTree:

    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

    def insert_left(self, value):
        if self.left == None:
            self.left = BinaryTree(value)

        else:
            new_node = BinaryTree(value)
            new_node.left = self.left
            self.left = new_node
    
    def insert_right(self, value):
        if self.right == None:
            self.right = BinaryTree(value)

        else:
            new_node = BinaryTree(value)
            new_node.right = self.right
            self.right = new_node
    
    def binInversion(self):

        if self.left is None and self.right is None:
            return 0

        else:
            binInversion(self.left)
            binInversion(self.right)
            self.left, self.right = self.right, self.left

a_node = BinaryTree('a')
a_node.insert_left('b')
a_node.insert_right('c')

b_node = a_node.left
b_node.insert_right('d')


c_node = a_node.right
c_node.insert_left('e')
c_node.insert_right('f')

d_node = b_node.right
e_node = c_node.left
f_node = c_node.right

a_node.binInversion()

另外,我知道binInversion() function 很有可能無法按預期工作。 不要透露反轉二叉樹的解決方案,因為我想在查看解決方案之前自己試一試。

這里有一些錯誤:

  1. binInversion 不是 function,它是 class 方法,記得調用self.binInversion()而不是binInversion()
  2. 在上述修復之后,仍然會出現一個錯誤,說明 binInversion 給出了太多 arguments。 您的 binInversion 方法不需要 arguments,嘗試使用def binInversion(self, node)之類的方法傳入另一個參數或節點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM