简体   繁体   English

为什么下面的代码会抛出错误?

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

So, I am trying to define a function which would invert a binary tree, and when I run the below code, and then execute a_node.binInversion() , I get the error which says, "NameError: name 'binInversion' is not defined".所以,我试图定义一个 function 来反转二叉树,当我运行下面的代码,然后执行a_node.binInversion()时,我收到错误消息,“NameError: name 'binInversion' is not defined ”。 Why is that error happening?为什么会发生这种错误?

The code I'm executing is as below:我正在执行的代码如下:

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()

Also, I know that there are high chances of binInversion() function not working as expected.另外,我知道binInversion() function 很有可能无法按预期工作。 Please DO NOT disclose the solution for inverting a binary tree, as I want to give it a shot on my own before looking at the solution.不要透露反转二叉树的解决方案,因为我想在查看解决方案之前自己试一试。

a few bugs here:这里有一些错误:

  1. binInversion is not a function, it is a class method, remember to call self.binInversion() instead of binInversion() binInversion 不是 function,它是 class 方法,记得调用self.binInversion()而不是binInversion()
  2. after the above fix, there will still be an error that says something along the lines of binInversion was given too many arguments.在上述修复之后,仍然会出现一个错误,说明 binInversion 给出了太多 arguments。 Your method of binInversion takes no arguments, try something like def binInversion(self, node) to pass in another argument or node.您的 binInversion 方法不需要 arguments,尝试使用def binInversion(self, node)之类的方法传入另一个参数或节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM