簡體   English   中英

將文本文件中的單詞插入樹(Java)

[英]Insert words from text file into tree (Java)

我需要將每個單詞放在文本文件中,並將它們添加到樹中。 我的第一個問題是不知道如何使用Java中的文件,然后我需要能夠插入單詞,但是如果有重復的單詞,它將增加該單詞的計數,而不是再次插入該單詞。 這些是我擁有的插入方法:

  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;
  }

有人可以幫我嗎?

您可以將一個名為count的實例變量添加到Node類,以便Node可以記住一段文本顯示了多少次。 您需要使Node構造函數將count設置為1

然后,您可以執行以下操作(有關其他操作,請參見粗體部分):


    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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM