1

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.

2 Answers 2

2

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.

new RBTree.RBNode();

should work if change class declaration of RBNode to

static class RBNode{}
Sign up to request clarification or add additional context in comments.

Comments

0

You need only use RBNode, not RBTree.RBNode. Furthermore do you really need a parent? RBNode can be private static.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.