【问题标题】:How to count the occurrence of an element in a tree?如何计算树中元素的出现次数?
【发布时间】:2014-02-18 01:26:20
【问题描述】:
   public int countOccurrences(String target){
       int count=0;
       node cursor=root;
       while(cursor!=null){

              int compare=target.compareTo(cursor.word);
               if(compare==0) {
                      //System.out.println("aa");  stuck in here
                      count++;
                   }
           else if(compare>0) cursor=cursor.right;
           else cursor=cursor.left;
       }

       System.out.println(count);
       return count;
   }

我想在树中查找单词的出现次数(已经按字典顺序排序)。我的代码现在一直在整个屏幕上打印出“aa”...帮助?

【问题讨论】:

标签: java string printing count tree


【解决方案1】:

您根本没有在 if 语句中更改光标,您只是在更改计数,这对光标没有影响,因此您会陷入无限循环。当您找到匹配项以及增加计数时,您需要更改光标。请参阅下面的示例:

if(compare==0) {
    //System.out.println("aa");  stuck in here
    count++;
    cursor = cursor.left 
}

这是假设它的排序方式,任何相等的都将在左分支中。如果相反,只需将cursor.left 更改为cursor.right

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 2018-10-19
    • 2022-11-30
    • 2021-04-07
    • 2010-10-05
    • 1970-01-01
    • 2014-09-30
    • 2020-06-09
    相关资源
    最近更新 更多