我试图打印出我的二叉树预订形式但是我遇到这些错误。我仍然在学习Python,所以我不太确定发生了什么。但我认为我的打印功能无法正常工作。不明白为什么preorder_print是有一个全局命名问题虽然=/打印预订中的BST
我的预期产出将是
pre order:
4
2
1
3
8
6
10
输出:
pre order:
<BST_tree.Node instance at 0x0000000002AA0988>
<BST_tree.Node instance at 0x0000000002AA0E08>
<BST_tree.Node instance at 0x0000000002AA0E88>
我的代码:
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:
preorder_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)
*编辑*
谢谢大家,特别是abarnert为您的帮助!这是固定版本!或preorder_print和BST_Inert
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)
if root.value < node.value: # go to right
if root.right is None:
root.right = node
else:
BST_Insert(root.right, node)
def preorder_print(root):
print root.value
if root.left is not None:
preorder_print(root.left)
if root.right is not None:
preorder_print(root.right)
坚持不住了,是你的问题的方式,节点打印出来,或者你只是g的事实而不是6? (另外,你在这里发布的代码仍然有[另一个问题]的错字(http://stackoverflow.com/questions/19170285/printing-bst-in-pre-order),所以没有人可以测试它来帮助你调试你的问题。) – abarnert
拍摄,但它实际上都是 – Liondancer
这确实有助于一次提出一个问题。许多人会争分夺秒地回答一个问题,然后离开,而你会遇到一半未解决的问题。最重要的是,如果其他人将来也有类似的问题,他将无法在搜索中找到你的回答良好的问题,因为这看起来像是一个关于与他的问题无关的问题。帮助有更多的信息是什么提出了一个很好的问题。 – abarnert