微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我如何成功地旋转这个 Treaps:随机搜索树?

如何解决我如何成功地旋转这个 Treaps:随机搜索树?

我想通过向树添加元素来构造一个 randomized search tree。从链接中的伪代码工作:

// Insert a new node in the tree and return the updated tree.
Algorithm insert(node,tree)
    if tree is empty
        return node
    if node.key < tree.key
        tree.left ← insert(node,tree.left)
        if tree.prio > tree.left.prio
            rotate tree to the right
    else
        tree.right ← insert(node,tree.right)
        if tree.prio > tree.right.prio
            rotate tree to the left
    return tree

我已经走到这一步了:

import random

class _Node:
    def __init__(self,data):
        self._left = None
        self._right = None
        self._key = data
        self._prio = random.randint(1,2**64)


class BinaryTree:
    def __init__(self):
        self._root = None
        self._size = 0

    def add(self,key,prio):
        node = _Node(key,prio)
        self._root = self.insert(node,self._root)

    def insert(self,node,tree):
        if tree is None:
            return node
        if node._key < tree._key:
            tree._left = self.insert(node,tree._left)
            if tree._prio > tree._left._prio: # <<<<< Rotation part
                tree._left._right = tree._left


        if node._key > tree._key:
            tree._right = self.insert(node,tree._right)
            if tree._prio > tree._right._prio: #<<<<< Rotation part
                tree._right._left = tree._right


        return tree

看看这个轮换:

   /            /
  G7           E3
 /  \     -->    \
E3                G7
                    \

我想分配 E3._right = G7。但是,我如何连接任何连接到 G7 的东西,即它是 E3 的父级?

非常感谢您的帮助,我已经坐这种方式很久了......

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。