<p>当然还是<code>None</code>。你没有给它赋值。应该是。你知道吗</p>
<pre><code>def Insert(self, data):
self.data = data
self.Recur(self.data, data)
</code></pre>
<p>但是,函数</p>
<pre><code>def Recur(self, node, data):
if node is None:
node = data
</code></pre>
<p>因为<code>node</code>没有在任何地方使用,只分配给。你知道吗</p>
<p>编辑:在更新代码之后,我们可以看到您正在尝试做什么。你的<code>test.root</code>之所以是<code>None</code>,是因为你从不分配它。问题在于:</p>
<pre><code>def insertRecur(self, node, data):
if node is None:
node = Node(data)
</code></pre>
<p>从<code>self.insertRecur(self.root, data)</code>调用此函数时,它指向与<code>self.root</code>相同的值,即<code>None</code>。当您执行<code>node = Node(data)</code>操作时,您正在重新指派<code>node</code>以指向<code>Note(data)</code>,这不会重新指派<code>self.root</code>。请改为:</p>
<pre><code>class Node:
"""A Tree Node with 3 attributes: l_child, r_child and data"""
def __init__(self):
self.data = None
self.l_child = None
self.r_child = None
class BST(object):
"""Implement a Binary Search Tree class"""
def __init__(self):
self.root = Node()
print "Initial root", self.root
def insertRecur(self, node, data):
if node.data is None:
node.data = data
elif data < node.data:
node.l_child = node.l_child or Node()
self.insertRecur(node.l_child, data)
else:
node.r_child = node.r_child or Node()
self.insertRecur(node.r_child, data)
def Insert(self, data):
self.insertRecur(self.root, data)
</code></pre>