关于pycharm:python没有定义递归函数?

Python not defined recursive function?

我在python3.5.0中创建了一个二叉树,并为它创建了insert函数。但当我在内部调用tree_insert时,我遇到了一个问题,它给了我这个错误:

File"D:/MadeUpPath/BinaryTree.py", line 10, in tree_insert

tree_insert(data, self.left)

NameError: name 'tree_insert' is not defined

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class BinaryTree():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def tree_insert(self, data):
        if (data < self.data):
            if (self.left != None):
                tree_insert(data, self.left)
            else:
                self.left = BinaryTree(data)
        else:
            if (self.right != None):
                tree_insert(data, self.right)
            else:
                self.right = BinaryTree(data)

进一步测试后,我发现递归函数根本不起作用。我尝试了以下代码来确定,但给出了相同的错误:

1
2
3
4
5
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

File"D:/MadeUpPath/BinaryTree.py", line 23, in factorial

return n * factorial(n - 1)

NameError: name 'factorial' is not defined

如果有人能给我指明正确的方向,我将不胜感激:)


tree_insert()为实例方法,通过self.tree_insert()调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class BinaryTree():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def tree_insert(self, data):
        if (data < self.data):
            if (self.left != None):
                self.tree_insert(data, self.left)
            else:
                self.left = BinaryTree(data)
        else:
            if (self.right != None):
                self.tree_insert(data, self.right)
            else:
                self.right = BinaryTree(data)