Search code examples
javatreenodered-black-tree

Need advice on how to create node class for r/b tree in java


We have been asked to implement a Red Black Tree in java, but not i'm exatcly sure how this is done. It would be really nice if anyone would comment on my node class for the r/b tree implementation. Here we go:

public class RBTnode {

public RBTnode(int key, RBTnode left, RBTnode right) {
    /* this is the constructor for a root node */
    color = 0;
    parent = null;
    key = this.key;
    left = this.left;
    right = this.right;
}

public RBTnode(int key, RBTnode left, RBTnode right, RBTnode parent, int color ) {
    key = this.key;
    color = this.color;
    left = this.left;
    right = this.right;
    parent = this.parent;

}

int color; // 0 black, 1 red
int key;
RBTnode parent;
RBTnode left;
RBTnode right;

}


Solution

  • I haven't written a RB tree myself, but I am learning about them right now. From what I've been told, It seems that you need some adjustments.

    There are certain rules that you need to follow in order for a RB Tree to be a RB Tree:

    • Every node is RED or BLACK
    • Root node is always BLACK
    • New nodes are always RED
    • Both children of a RED node is BLACK.
    • Every path from a root to a leaf, or to a null child, must contain the same number of black nodes.

    That being said, I don't think you need the second constructor because no matter what, you are always going to initialize a new node to RED.