我正在尝试以预购形式打印出我的二叉树,但是我遇到了这些错误。我还在学习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)