0

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;

}

John
  • 317
  • 4
  • 19
  • So what's about your code? Is it working? Is there a problem (which)? ... what is your question? – Kai Apr 17 '12 at 18:15
  • I'm wondering whether it is a good idea to create two constructors like I did, because we will only need the first constructor once obviously, as we only have 1 root? Also is it the right move to assign the parent node as well as the children as a RBTnode? I dont know if it works yet, but my idea is that i want to create a arraylist, which should contain RBTnode objects, in another class togehter with the methods (insert, traverse tree etc.). – John Apr 17 '12 at 18:24
  • 2
    maybe turn around `parent = this.parent;` etc ? :) – zapl Apr 17 '12 at 18:39

1 Answers1

1

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.

Charles Menguy
  • 40,830
  • 17
  • 95
  • 117
Kyle
  • 366
  • 3
  • 17
  • Im learning about them as well, so i know all those requirements for a binary search tree to be a r/b tree, but yes, i think it's too much with 2 constructors. – John Apr 17 '12 at 22:54
  • Make the first constructor call the second and it's all a moot point. That's just the basics of good code, unrelated to whatever you're doing. – Kevin Apr 18 '12 at 05:29