2016-11-18 80 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; 
}