我正在尝试以预订形式打印出我的二叉树,但是我遇到了这些错误。我还在学习python,所以我不太确定发生了什么。但我认为我的打印功能无法正常工作。不太清楚为什么preorder_print有一个全局名称问题= =
输出:
>>> from BST_tree import *
pre order:
<BST_tree.Node instance at 0x0000000002AA0C88>
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from BST_tree import *
File "BST_tree.py", line 51, in <module>
preorder_print(r)
File "BST_tree.py", line 27, in preorder_print
preoder_print(root.left)
NameError: global name 'preoder_print' is not defined
我的代码:
class Node:
def __init__(self,value):
self.right = None
self.left = None
self.value = value
def BST_Insert(root, node): # root --> root of tree or subtree!
if root.value is None:
root = node # beginning of tree
else:
if root.value > node.value: # go to left
if root.left is None:
root.left = node
else:
BST_Insert(root.left, node)
else:
if root.value < node.value: # go to right
root.right = node
else:
BST_Insert(root.right, node)
def preorder_print(root):
print root
if root.left is not None:
preoder_print(root.left)
else:
if root.right is not None:
preorder_print(root.right)
r = Node(4)
# left
a = Node(2)
b = Node(1)
c = Node(3)
# right
d = Node(8)
e = Node(6)
f = Node(10)
BST_Insert(r, a)
BST_Insert(r, b)
BST_Insert(r, c)
BST_Insert(r, d)
BST_Insert(r, e)
BST_Insert(r, f)
print "pre order:"
preorder_print(r)
答案 0 :(得分:1)
这是一个简单的拼写错误:您定义了preorder_print
,但尝试拨打preoder_print
。
当您看到如下错误消息时:
NameError: global name 'preoder_print' is not defined
...不要太担心“全球”部分。问题是名称没有定义任何地方,甚至在全局变量中也没有定义。*所以,开始寻找未定义的原因。
像这样的错别字很容易制作,所以这通常是我检查的第一件事:从错误信息中复制字符串,然后将其粘贴到搜索中。*这有点过于简单,但现在还不错。 实际意味着首先编译器在编译时无法将其作为本地或闭包名称找到,因此假设它是一个全局名称,然后解释器找不到它全局或在运行时内置。