【发布时间】:2017-03-26 00:59:40
【问题描述】:
我有一个二叉搜索树,其中每个节点(GameEntry 类)代表一个“游戏玩法”(名称/分数对)。树是按名称(不是分数)组织的。我正在尝试为树编写一个方法来打印其前十名分数的列表(具有相应的名称)。我想过递归地遍历树,如果(且仅当)它是高分时,将一个节点放入一个数组(ScoreBoard 类)中。它有效,除了我的问题是记分牌会打印递归中的每一步。
public void printTopTen()
{
ScoreBoard board = new ScoreBoard(10); // new scoreboard with capacity of 10
printTopTenRecur(this.root, board);
}
// Auxillary method for printTopTen()
private void printTopTenRecur(GameEntry node, ScoreBoard board)
{
if (node == null)
{
return;
}
printTopTenRecur(node.getLeft(), board);
board.add(node); // adds the node to the scoreboard if it's a high score
System.out.println(board);
printTopTenRecur(node.getRight(), board);
}
我唯一能想到的就是在类上创建一个属性(称为board),然后在递归完成后打印出该属性。但是我收到了编译时错误void cannot be converted to String。我不知道还能怎么做。
public String printTopTen()
{
ScoreBoard board = new ScoreBoard(10); // new scoreboard with capacity of 10
printTopTenRecur(this.root, board);
return System.out.println(this.board);
}
// Auxillary method for printTopTen()
private void printTopTenRecur(GameEntry node, ScoreBoard board)
{
if (node == null)
{
return;
}
printTopTenRecur(node.getLeft(), board);
board.add(node); // adds the node to the score board if it's a high score
this.board = board; // assign local board to the board on the tree
printTopTenRecur(node.getRight(), board);
}
【问题讨论】:
标签: java recursion data-structures