简体   繁体   中英

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". 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. 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()
  2. after the above fix, there will still be an error that says something along the lines of binInversion was given too many arguments. Your method of binInversion takes no arguments, try something like def binInversion(self, node) to pass in another argument or node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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