简体   繁体   中英

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?

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);
      }
      
      return parent;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM