双向二叉搜索树?

时间:2019-07-08 19:25:38

标签: 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循环而不是递归是一个坏主意?

2 个答案:

答案 0 :(得分:1)

带有父链接的BST有时会被使用。

好处不是链接使搜索或更新变得更容易(它们并非如此),而是可以在任何给定节点之前或之后插入,或者从该节点向前或向后遍历而无需搜索从根开始。

使用指向节点的指针来表示树中的位置(而不是完整路径)变得很方便,即使树中包含重复项,并且当在其他位置执行更新或删除操作时,该位置仍然有效。

例如,在抽象数据类型中,这些属性使提供易于被突变无效的迭代器变得容易。

答案 1 :(得分:0)

您尚未描述如何通过父指针获得任何收益。关心回退到父节点的算法将通过爬回调用堆栈来实现。

我去过那里-在我的数据结构类中,我用双向指针实现了我的东西。当我们进入二叉树时,那些指针不再有用。正确使用递归代替了跟踪链接以备份树的需要。