';无';用python
上面我有一个简单的程序,它从排序数组创建BST。它应该解析树而不显示本质上没有的叶子。有人能解释一下为什么这个程序仍然“一个也没有”吗。我是一个python NooB,非常感谢您的帮助。我已经尝试过了!='“None”与“None”一起是“None”,但会得到相同的结果';无';用python,python,python-2.7,Python,Python 2.7,上面我有一个简单的程序,它从排序数组创建BST。它应该解析树而不显示本质上没有的叶子。有人能解释一下为什么这个程序仍然“一个也没有”吗。我是一个python NooB,非常感谢您的帮助。我已经尝试过了!='“None”与“None”一起是“None”,但会得到相同的结果 class Node: def __init__(self,value): self.value=value self.nodeleft=None self.noderig
class Node:
def __init__(self,value):
self.value=value
self.nodeleft=None
self.noderight=None
def makeBST(ia,start,end,tree):
if (end < start):
return None
mid = (start + end) / 2
n = Node(ia[mid])
n.nodeleft = makeBST(ia, start, mid-1, tree)
n.noderight = makeBST(ia, mid+1, end, tree)
tree.append(n)
return n
def printBST(root):
print 'RR' ,root.value
if root.nodeleft == None:
print 'EOT'
else:
print printBST(root.nodeleft)
if root.noderight == None:
print 'EOT'
else:
print printBST(root.noderight)
if __name__ == '__main__':
array = [1, 2, 3, 4, 5, 6]
dic = []
root = makeBST(array, 0, len(array)-1, dic)
printBST(root)
类节点:
定义初始值(自身,值):
自我价值=价值
self.nodeleft=无
self.noderRight=无
def makeBST(ia、开始、结束、树):
如果(结束<开始):
一无所获
中间=(开始+结束)/2
n=节点(ia[mid])
n、 nodeleft=makeBST(ia、start、mid-1、tree)
n、 noderRight=makeBST(ia、mid+1、end、tree)
tree.append(n)
返回n
def printBST(根目录):
打印'RR',root.value
如果root.nodeleft==无:
打印“EOT”
其他:
打印printBST(root.nodeleft)
如果root.noderRight==无:
打印“EOT”
其他:
打印printBST(root.noderRight)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
数组=[1,2,3,4,5,6]
dic=[]
root=makeBST(数组,0,len(数组)-1,dic)
printBST(根目录)
printBST
应该返回值,而不是打印值。因为它不返回任何内容,所以默认为None
。这就是为什么printBST(root)是None
printBST(root)
本身不会单独打印值。您必须在以下内容之前放置打印
:
print printBST(root)
根据,永远不要将非类型单例与相等运算符进行比较(例如=
和!=
)。使用是无的
和/或不是无的
问题是您的代码将printBST
的返回值传递到print
。由于printBST
不返回任何内容,因此打印了None
所以当你写的时候:
print printBST(root.nodeleft)
该代码肯定会打印None
,因为printBST
不包含返回语句,因此默认为返回None
要执行此操作,您需要更改printBST
:
def printBST(root):
print 'RR' ,root.value
if root.nodeleft is None:
print 'EOT'
else:
printBST(root.nodeleft)
if root.noderight is None:
print 'EOT'
else:
printBST(root.noderight)
还请注意,使用is
是测试无的正确方法
也就是说,您可以像这样简化代码:
def printBST(root):
if root is None:
print 'EOT'
return
print 'RR', root.value
printBST(root.nodeleft)
printBST(root.noderight)
除了更简单之外,这段代码还有一个额外的好处,就是当出现一个空树时不会失败。我没有投反对票,但答案没有多大意义。看起来非常像printBST
的设计实际上是它应该打印树。把它修好让它按预期工作并不困难。而且printBST(root)
确实是None
,但是它永远不会被打印出来。打印的是printBST(root.nodeleft)
和printBST(root.noderight)
。你应该问自己为什么要增加选票!;-)