I am writing a program to implement the Red-Black Tree data structure in java. Below is the beginning of my implementation, namely the left and right rotate functions. I want to know if these functions are correct, and if not, any tips on correcting them. I am basing my functions off of pseudocode I found. Here is a link to the pseudocode I used. If you need to see the node class let me know however I think it is self explanatory for the most part.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rbtree;
/**
*
* @author williamnewman
*/
public class RBTree {
node root;
RBTree(int val){
node r = new node();
r.setVal(val);
this.root = r;
}
void leftRotate(node x){
node y = x.rightChild;
x.rightChild = y.leftChild;
if(y.leftChild != null){
y.leftChild.parent = x;
}
y.parent = x.parent;
if(x.parent == null)
this.root = y;
else if(x == x.parent.leftChild){
x.parent.leftChild = y;
}
else{
x.parent.rightChild = y;
}
y.leftChild = x;
x.parent = y;
}
void rightRotate(node x){
node y = x.leftChild;
x.leftChild = y.rightChild;
if(y.rightChild != null){
y.rightChild.parent = x;
}
y.parent = x.parent;
if(x.parent == null){
this.root = y;
}
else if(x == x.parent.rightChild){
x.parent.rightChild = y;
}
else{
x.parent.leftChild = y;
}
y.rightChild = x;
x.parent = y;
}
}
1 Answer 1
- In Java class names should start with an upper letter (
node
->Node
). - Why all your methods have default visibility? You usually want to have public methods though if this intentional then just ignore this point.
- You seem to be restricting your
RBTree
to have onlyint
s. You could use generics instead to make it more flexible and make it useful in more cases - Your formatting is inconsistent (indentation).
-
\$\begingroup\$ The functions will work though? \$\endgroup\$Will– Will2017年07月16日 20:56:36 +00:00Commented Jul 16, 2017 at 20:56
-
\$\begingroup\$ It should but the best way to know it is just to test it. The more tests (testing different cases) the more confident can you be that it works exactly as you want. From what I see though it should be okay \$\endgroup\$Mibac– Mibac2017年07月16日 20:58:22 +00:00Commented Jul 16, 2017 at 20:58