peppercumin
peppercumin

Reputation: 19

Insert words from text file into tree (Java)

I need to take each word in a text file and add them to a tree. My first problem is not knowing how to work with files in Java, and then I need to be able to insert words, but if there's a duplicate word it increases a counter for that word, rather than inserting the word again. These are the insert methods I have:

  public void insert(String txt)
  {
    this.root = insert(root, new Node(txt));
  }

  private Node insert(Node parent, Node newNode)
  {
    if (parent == null)
    {
      return newNode;
    }
    else if (newNode.data.compareTo(parent.data) > 0)
    {
      parent.right = insert(parent.right, newNode);
    }
    else if (newNode.data.compareTo(parent.data) < 0)
    {
      parent.left = insert(parent.left, newNode);
    }
    return parent;
  }

Could anyone help me out?

Upvotes: 0

Views: 1464

Answers (1)

Chai T. Rex
Chai T. Rex

Reputation: 3007

You can add an instance variable called count to the Node class so that the Node can remember how many times a piece of text has shown up. You'll need to make the Node constructor set the count to 1.

Then, you can do something like this (see the bold part for what to do differently):


    public void insert(String txt)
    {
      root = insert(root, new Node(txt));
    }

    private Node insert(Node parent, Node newNode)
    {
      if (parent == null)
      {
        return newNode;
      }

      final int comparison = newNode.data.compareTo(parent.data)
      if (comparison > 0)
      {
        parent.right = insert(parent.right, newNode);
      }
      else if (comparison < 0)
      {
        parent.left = insert(parent.left, newNode);
      }
      else { // If the new text matches the text of this node.
        parent.count++;
      }
      return parent;
    }

Upvotes: 0

Related Questions