我已经尝试实现 BST。截至目前,它仅根据 BST 属性(左下,右大)添加键。尽管我以不同的方式实现了它。
我认为 BST 应该是这样的
我是如何实现我的 BST
问题是它是否是 BST 的正确实现? (我在双面 BST 中看到它的方式会更容易搜索、删除和插入)
import pdb;
class Node:
def __init__(self, value):
self.value=value
self.parent=None
self.left_child=None
self.right_child=None
class BST:
def __init__(self,root=None):
self.root=root
def add(self,value):
#pdb.set_trace()
new_node=Node(value)
self.tp=self.root
if self.root is not None:
while True:
if self.tp.parent is None:
break
else:
self.tp=self.tp.parent
#the self.tp varible always is at the first node.
while True:
if new_node.value >= self.tp.value :
if self.tp.right_child is None:
new_node.parent=self.tp
self.tp.right_child=new_node
break
elif self.tp.right_child is not None:
self.tp=self.tp.right_child
print("Going Down Right")
print(new_node.value)
elif new_node.value < self.tp.value :
if self.tp.left_child is None:
new_node.parent=self.tp
self.tp.left_child=new_node
break
elif self.tp.left_child is not None:
self.tp=self.tp.left_child
print("Going Down Left")
print(new_node.value)
self.root=new_node
newBST=BST()
newBST.add(9)
newBST.add(10)
newBST.add(2)
newBST.add(15)
newBST.add(14)
newBST.add(1)
newBST.add(3)
编辑:我使用了 while 循环而不是递归。有人可以详细说明为什么在这种特殊情况下和一般情况下使用 while 循环而不是递归是个坏主意吗?
最佳答案
偶尔会使用带有父链接的 BST。
好处不是链接使搜索或更新更容易(实际上并非如此),而是您可以在任何给定节点之前或之后插入,或者从该节点向前或向后遍历,而无需搜索从根开始。
使用指向节点的指针来表示树中的位置变得很方便,而不是完整路径,即使树包含重复项,并且该位置在其他地方执行更新或删除时仍然有效。
在抽象数据类型中,这些属性使它变得容易,例如,提供不会因突变而失效的迭代器。
关于python - 双向二叉搜索树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56941413/