I need to implement a red-black search tree in java. I thought about creating two class: RBTree and RBNode, where RBNode is nested inside RBTree (this is the demand of the exercise).
RBNode should have the following fields:
key, value, color – no problem with that.
parent, leftChild, rightChild – which are also RBNode type. This I cannot seem to implement, because in order to create an instance of an RBNode, I need an instance of RBTree.
This is my code:
public class RBTree {
public RBNode createNode() {
return this.new RBNode();
}
class RBNode{
private int key;
private RBTree.RBNode rightChild = new RBTree.RBNode(); \//the problem is here
public RBNode() {
this.rightChild=null;
this.key=-1;
}
}
public static void main(String[] args) {
RBTree t = new RBTree();
RBNode rb = t.createNode();
System.out.println(rb.key);
System.out.println(rb.rightChild.key);
}
}
I would appreciate any ideas how to solve this.
Thanks.
there is no point in making RBNode as a nested class.
Make RBNode a separate class and store a reference to RBNode in RBTree. It should solve your problem.
In case, you want to make a nested class, make it static class so that you dont have to instantiate the parent class to instantiate RBNode.
should work if change class declaration of RBNode to