0

I want to construct a randomized search tree by adding elements to a tree. Working from the Pseudocode in the link:

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

I've come this far:

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

Looking at this rotation:

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

I want to assign E3._right = G7. However, how do I connect whatever thats connected to G7, i.e it's parent to E3?

Any help is muy appreciated, I've been sitting with this way to long....

Oskar
  • 97
  • 2

0 Answers0