2016-11-18 84 views
0

我在編寫我的代碼項目時遇到了一些麻煩。該程序是一個保存WordCount對象的二進制搜索樹。這些只包含兩個字段,一個字的字符串和一個整數,該整數保存該單詞出現在文本文件中的次數。Java - 如何遍歷二叉搜索樹遞歸無參數

我遇到麻煩的方法需要遍歷樹以找到最常用的單詞。我已經實現了一個方法,可以做到這一點,但我發現該方法應該是遞歸的,而不是使用參數。

我已經寫的方法是在這裏:

WordCount getMostCommonWord(BinaryTreeNode<WordCount> wordNode) 
     throws EmptyCollectionException { 

    WordCount current = wordNode.getElement(); 

    BinaryTreeNode left = wordNode.getLeftChild(); 
    BinaryTreeNode right = wordNode.getRightChild(); 

    WordCount maxLeft; 
    WordCount maxRight; 

    if (left != null) { 
     maxLeft = getMostCommonWord(left); 
     if (current.getCount() < maxLeft.getCount()) { 
      current = maxLeft; 
     } 
    } 

    if (right != null) { 
     maxRight = getMostCommonWord(right); 
     if (current.getCount() < maxRight.getCount()) { 
      current = maxRight; 
     } 
    } 

    return current; 
} 

這也是我第一次張貼在這裏,很抱歉,如果我做錯了。有關如何在沒有參數的情況下工作的任何提示都會有所幫助。提前致謝!

+1

只需重構,以便使用'this'而不是'wordNode'。和'left.getMostCommonWord()'而不是'getMostCommonWord(left)'。 – 4castle

+0

什麼是二叉樹排序?如果它按字數排序,並且您想要字數最高的節點,那麼這將是最右側(如果是最下方的)節點。遞歸將是「如果我有權利,返回我的權利的結果,否則返回我的結果」 –

回答

0

你很近。由於您無法使用參數,因此請直接在節點類上使用此方法。然後使用this

這有一個通用的優點,但需要在您的情況下,T,wordCount,實施Comparable

BinaryTreeNode<T> getMaxNode() 
     throws EmptyCollectionException { 

    BinaryTreeNode<T> left = this.getLeftChild(); 
    BinaryTreeNode<T> right = this.getRightChild(); 

    BinaryTreeNode<T> currentMax = this; 
    BinaryTreeNode<T> maxLeft; 
    BinaryTreeNode<T> maxRight; 

    if (left != null) { 
     maxLeft = left.getMaxNode(); 
     if (this.getElement() < maxLeft.getElement()) { 
      currentMax = maxLeft; 
     } 
    } 

    if (right != null) { 
     maxRight = right.getMaxNode(); 
     if (this.getElement() < maxRight.getElement()) { 
      currentMax = maxRight; 
     } 
    } 

    return currentMax; 
}