繁体   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