DomX23
DomX23

Reputation: 887

Node for BST in Java

I'm having some trouble with writing a node for my Binary Search Tree. I know it should point to the left child and right child, and in the data field it will have a string, but I also want it to point to an arraylist. Which is the part I'm not sure how to code myself in java.

class BSTNode {

    BSTNode( Comparable theString ) {
        element = theString;
        left = right = null;
    }

    Comparable element;      // The data in the node
    BSTNode left;         // Left child
    BSTNode right;        // Right child
}

Upvotes: 1

Views: 733

Answers (1)

Grady S
Grady S

Reputation: 350

To also have an ArrayList<String> at each node, you simply add an ArrayList<String> field to the node class like this:

public class BSTNode {
    private String value;
    private ArrayList<String> listOfStrings;
    private BSTNode left;
    private BSTNode right;

    // Constructor and other methods here

}

Then, on top of the normal BST methods, you will probably want to add accessor and mutator methods for your ArrayList<String> field. How that is done obviously depends on what you intend to do with the tree.

Here's an example of a simple method to add a string to the ArrayList<String>:

 public void addStringToList(String str) {
   this.listOfStrings.add(str);
 }

An example of a method to get the whole ArrayList<String>:

 public ArrayList<String> getList() {
   return this.listOfStrings;
 }

These methods would go right in the body of the BSTNode class.

If I didn't answer your question, consider editing your question to clarify.

Upvotes: 3

Related Questions