NameError: name 'heigth' is not defined

NameError: name 'heigth' is not defined

我对python没有经验。

我正在上大学 activity 我写了一个 class 来求二叉树的高度。

但是当我要递归调用该函数时,我收到消息:

NameError                                 Traceback (most recent call last)
<ipython-input-5-109fbd93416e> in <module>
      7 raiz.insert(3)
      8 
----> 9 heigth(raiz)

NameError: name 'heigth' is not defined 

函数是:

def heigth(self, n:"Node")-> int:
        if n:
            return 1
        else:
            left = heigth(n.left)
            right = heigth(n.right)
            if(left < right):
                return right + 1
            else:
                return left + 1

所有代码:

from typing import List

class Node:
    def __init__(self, key, left:"Node"=None, right:"Node"=None):
        self.key = key
        self.left = left
        self.right = right

    def print_tree(self):
        """
        Prints the tree from the current node
        """
        if self.left:
            self.left.print_tree()
        print(self.key, end=" ")
        if self.right:
            self.right.print_tree()


    def insert(self, key) -> bool:
        """
        Insert a node in the tree that has the key "key"
        """
        if key < self.key:
            if self.left:
                return self.left.insert(key)
            else:
                self.left = Node(key)
                return True
        elif key > self.key:
            if self.right:
                return self.right.insert(key)
            else:
                self.right = Node(key)
                return True
        else:
            return False


    def search(self, key) -> bool:
        """
        Returns true if the key exists in the tree
        """
        if key < self.key:
            if self.left:
                return self.left.search(key)
        elif key > self.key:
            if self.right:
                return self.right.search(key)
        else:
            return True
        return False


    def to_sorted_array(self, arr_result:List =None) -> List:
        """
        Returns a vector of the ordered keys.
        arr_result: Parameter with the items already added.
        """
        if(arr_result == None):
            arr_result = []

        if self.left:
            self.left.to_sorted_array(arr_result)

        arr_result.append(self.key)

        if self.right:
            self.right.to_sorted_array(arr_result)
        return arr_result

    def max_depth(self,current_max_depth:int=0) -> int:
        """
        calculates the greatest distance between the root node and the leaf
        current_max_depth: Value representing the longest distance so far
                           when calling for the first time, there is no need to use it
        """
        current_max_depth = current_max_depth +1
        val_left,val_right = current_max_depth,current_max_depth

        if self.left:
            val_left = self.left.max_depth(current_max_depth)
        if self.right:
            val_right = self.right.max_depth(current_max_depth)

        if(val_left>val_right):
            return val_left
        else:
            return val_right

    def position_node(self, key, current_position:int=1) -> int:
        """
            Returns the position of the desired node in the tree
            current_position: represents the position of the tree at that moment
                           when calling for the first time, there is no need to use it
        """
        if key < self.key:
            if self.left:
                return self.left.position_node(key, current_position*2)
        elif key > self.key:
            if self.right:
                return self.right.position_node(key, current_position*2+1)
        else:
            return current_position

    def heigth(self, n:"Node")-> int:
        if n:
            return 1
        else:
            left = heigth(n.left)
            right = heigth(n.right)
            if(left < right):
                return right + 1
            else:
                return left + 1

您不能调用 class 中的函数,您必须首先使用 self 调用 class 而不是函数:

left = self.height(n.left)
right = self.height(n.right)

您正在使用 class 的方法,但是当您将它作为 heigth 引用时,它查找的方法不是在对象的 class 中,而是在找不到它的模块级别,因此出现错误。

尝试用 self.heigth 替换 heigth 调用,以便调用 class 的方法。

您可以使 height 成为 Node 的静态方法。

您必须使用 raiz 实例作为参数调用 height 方法。

class Node:
# ...
    @staticmethod
    def height(n:"Node")-> int:
        return 1 + max(self.height(n.left), self.height(n.right)) if n else 0

raiz.insert(3)
print(Node.height(raiz))

或者做成递归的方法

class Node:
# ...
    def _height(self, n:"Node") -> int:
        return n.height() if n else 0
    def height(self) -> int:
        return 1 + max(self._height(self.left), self._height(self.right))

raiz.insert(3)
print(raiz.height())