设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 重新 数据 创业者
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

Treap――堆和二叉树的完美结合,性价比极值的搜索树(5)

发布时间:2020-12-15 10:55 所属栏目:21 来源:网络整理
导读:defreset_child(self,node,child,left_or_right='left'):"""Resetthechildoffather,sinceinPythonalltheinstancespassedbyreference,soweneedtosetthenodeasachildofitsfathernode."""ifnodeisNone:self.root=child

def reset_child(self, node, child, left_or_right='left'):        """        Reset the child of father, since in Python all the instances passed by reference, so we need to set the node as a child of its father node.        """        if node is None:            self.root = child            self.root.father = None            return        if left_or_right == 'left':            node.lchild = child        else:            node.rchild = child        if child is not None:            child.father = node   def rotate_left(self, node, father, left_or_right):        """        Left rotate operation of Treap.        Example:                  D              /                A      B                   /                   E   C         After rotate:                 B               /               D   C             /             A   E         """        rchild = node.rchild        node.rchild = rchild.lchild        if rchild.lchild is not None:            rchild.lchild.father = node        rchild.lchild = node        node.father = rchild        self.reset_child(father, rchild, left_or_right)        return rchild     def rotate_right(self, node, father, left_or_right):        """        Right rotate operation of Treap.        Example:                  D              /                A     B            /            E   C         After rotate:                 A               /               E   D                 /                 C   B         """        lchild = node.lchild        node.lchild = lchild.rchild        if lchild.rchild is not None:            lchild.rchild.father = node        lchild.rchild = node        node.father = lchild        self.reset_child(father, lchild, left_or_right)        return lchild 

这里唯一要注意的是,由于Python当中存储的都是引用,所以我们在旋转操作之后必须要重新覆盖一下父节点当中当中的值才会生效。负责我们修改了node的引用,但是father当中还是存储的旧的地址,一样没有生效。

后记

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读