python - 双向二叉搜索树?

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

我已经尝试实现 BST。截至目前,它仅根据 BST 属性(左下,右大)添加键。尽管我以不同的方式实现了它。

我认为 BST 应该是这样的

Single Direction BST

我是如何实现我的 BST

Bi-Directional 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/

相关文章:

Python如何在运行脚本处理文件时传入一个可选的文件名参数

python - 在 OpenCV + Python 中计算汽车

python - Canonical Celery 单文件 hello world

python - 为什么python3写文件比python2慢

python - 如何使用随机列表中的特定数字打印python执行时间以输出时间和生成的随机数?

.net - 在平面上画线的算法

php - 安装或未安装 Python 模块?

python - 从数据框中选择事件出现前的最后 n 条记录

database - 设计 - 动态数据映射

JavaScript 数组 : Algorithm sorting and picking