hi,

need some help with these rotations guys, going mental now, stucked with it for two days already...

trying to implement a balanced binary tree (also known as TREAP), where nodes inserted have both key and priority value. general rules are:

if node A is left child of node B -> key[A] < key[B]

if node A is right child of node B -> key[A] > key[B]

thats the easy part.

additional condition in the treap structure is as follows:

if A is a child of B -> priority(A) > priority(B)

which messes everything up, 'cos now with every insertion, if the priority of new node is smaller than we have to rotate the tree, either to the left or right.

ok, enough theory, here is the code that I've come up with so far, for inserting a new node :

public void insert(char id, double dd) { Node newNode = new Node(); // make new node newNode.iData = id; // key value newNode.dData = dd; // priority value if(root==null) // no node in root root = newNode; else if(root != null) // root occupied { Node current = root; // start at root Node parent; Node temp; while(true) // (exits internally) { parent = current; if(id < current.iData && dd > current.dData) // go left? { current = current.leftChild; if(current == null) // if end of the line, { // insert on left parent.leftChild = newNode; return; } } // end if go left else if(id < current.iData && dd < current.dData) { if(parent == null) { root = newNode; } else { temp = current; current = newNode; newNode.leftChild = temp.rightChild; temp.rightChild = temp; return; } } else if(id > current.iData && dd > current.dData) // or go right? { current = current.rightChild; if(current == null) // if end of the line { // insert on right parent.rightChild = newNode; return; } } else if(id > current.iData && dd < current.dData) { if(parent == null) { root = newNode; } else { temp = current; current = newNode; newNode.rightChild = temp.leftChild; temp.leftChild = temp; return; } } // end else go right } // end while } // end else not root } // end insert()

any comments, hints suggestions.. anything !!! would be great, don't want to go completly bonkers, with xmas so close