【发布时间】:2020-09-25 23:02:39
【问题描述】:
我正在尝试在 python 中使用 dict 构建 BST(二叉搜索树)。我不明白为什么我的代码没有向 BST 添加节点。我在这里看到了一个类似的帖子: How to implement a binary search tree in Python? 除了声明一个节点类外,它看起来与我的代码相同,但我想知道为什么我的 dict 实现失败(并希望提高我对在 python 中使用递归传递参数的理解)。
keys = [10,9,2,5,3,7,101,18]
start = {'key': keys[-1], 'val': 1, 'left': None, 'right': None}
def binarySearch(root, node):
# compare keys and insert node into right place
if not root:
root = node
elif node['key'] < root['key']:
binarySearch(root['left'], node)
else:
binarySearch(root['right'], node)
# Now let's test our function and build a BST
while keys:
key = keys.pop()
node = {'key': key, 'val': 1, 'left': None, 'right': None}
binarySearch(start, node)
print(start) # unchanged, hence my confusion. Thx for your time!
=============================================
编辑:这是使它工作的代码!
def binarySearch(root, node):
# compare keys and insert node into right place
if not root:
root = node
elif node['key'] < root['key']:
if not root['left']: root['left'] = node
else: binarySearch(root['left'], node)
else:
if not root['right']: root['right'] = node
else: binarySearch(root['right'], node)
以下是我认为幕后发生的事情(为什么一个版本能够添加到 BST 而另一个版本不能):
在最初的版本中,我们将到达一个递归调用,其中root 仍然指向BST 中的None,但随后root = node 使root 指向node,它与start 完全没有联系,即 BST 本身。然后局部变量被删除,不做任何更改。
在修改后的版本中,我们将避免这种情况,因为当我们添加节点时,例如root['left'] = node。这里root 仍然指向原始BST,因此我们正在修改原始BST 中的key-val 对,而不是让root 指向完全在BST 之外的东西。
【问题讨论】:
-
root = node定义了一个名为root的新局部变量。你是这个意思吗? -
链接问题的接受答案处理 left 或 right 为 None 而不是递归。
-
函数根内部的@ForceBru 是传递给函数的第一个参数,独立于外部的根。我已经编辑了代码以消除任何混乱。
-
@quamrana 他们能够将节点插入到根目录,所以我想我可以对 dict 做同样的事情,但我不确定它为什么会失败..
标签: python recursion parameter-passing binary-search-tree