插入功能使bst无法正常工作

时间:2017-12-25 16:28:52

标签: python-3.x binary-search-tree

如果有人可以帮我提交递归部分? 我省略了一些部分,认为这不是必要的,但是在那个功能不起作用之后。

<BrowserRouter>
<Switch>
  <Route exact path='/login/' component={Login} />
  <Redirect exact from='/' to='/login/' />
  <Route exact path='/sample/' component={sample} />
</Switch>

1 个答案:

答案 0 :(得分:0)

因为您需要为空分支创建新的node个实例。

让我们看看这两个定义会发生什么,打印出Node参数的值:

def insert(Node, value):
  print(Node)
  if Node is None:
    Node=node(value)
  else:
    if value<Node.data:
      insert(Node.left,value)
    else:
      insert(Node.right,value)

在REPL上:

In [17]: badTree = node(10)

In [18]: badTree.data
Out[18]: 10

In [20]: badTree.left.data
----------------------------------------------------------------------
AttributeError                       Traceback (most recent call last)
<ipython-input-20-3cb52def2967> in <module>()
----> 1 badTree.left.data

AttributeError: 'NoneType' object has no attribute 'data'

In [21]: badTree.right.data
----------------------------------------------------------------------
AttributeError                       Traceback (most recent call last)
<ipython-input-21-b6f1267c9d29> in <module>()
----> 1 badTree.right.data

AttributeError: 'NoneType' object has no attribute 'data'

让我们看看如果我们向badTree插入一个元素会发生什么:

In [22]: insert(badTree, 2)
<__main__.node object at 0x7f706bf34d30>
None

In [23]: badTree.left.data
----------------------------------------------------------------------
AttributeError                       Traceback (most recent call last)
<ipython-input-23-3cb52def2967> in <module>()
----> 1 badTree.left.data

AttributeError: 'NoneType' object has no attribute 'data'

它无法插入元素,但为什么?在badTree中,leftright分支都是None(空),这意味着我们需要在那里创建新树,因为我们无法在递归添加新值,因为我们丢失了对主Node的引用。这是,如果我们在将新对象分配给insert(Node.left, value)之前调用Node.left,则相当于调用insert(None, value)(此值None,您可以在我们看到它时看到它在insert)上调用badTree,它将递归调用insert并执行None = node(value),这将无效。

如果我们改用这个定义会发生什么:

def insert(Node, value):
  print(Node)
  if Node is None:
    Node = node(value)
  else:
    if value < Node.data:
      if Node.left is None:
        Node.left = node(value)
      else:
        insert(Node.left, value)
    else:
      if Node.right is None:
        Node.right = node(value)
      else:
        insert(Node.right, value)

在REPL上:

In [25]: newTree = node(4)

In [26]: insert(newTree, 10)
<__main__.node object at 0x7f706bf30668>

In [27]: insert(newTree, 12)
<__main__.node object at 0x7f706bf30668>
<__main__.node object at 0x7f706bf30a58>

现在看到它不再失败了,因为我们正在跟踪树节点中的内存地址,因此我们可以引用那些允许我们就地插入的对象(树)。 / p>

相关问题