gpt4 book ai didi

java - BST 最小 n 个元素显示

转载 作者:行者123 更新时间:2023-12-02 10:56:15 25 4
gpt4 key购买 nike

我有这个方法,它应该在屏幕上显示 BST 中最小的 n 个元素,例如 n=3,最小的 3 个元素等等..

不幸的是,在运行时,它显示它达到了空内容并被关闭。进一步说明,该方法应该返回 int 并且它不是 void,但我找不到另一种方法来显示所有元素,因为返回类型 int 只会给出一个元素?正确的?

public int sorteduptp(int n) {
if (n > 0 && !isEmpty()) {
BinarySearchTree current = this;

while (!current.leftChild.isEmpty() && current.size() != n) {
current = current.leftChild;

}
if (n == 1) {
System.out.println(current.leftChild.getContent());
return 0;

} else {
sorteduptp(n - 1);
while (!current.isLeaf()) {
System.out.println(current.getContent());
System.out.println(current.rightChild);
}
System.out.println(current.getContent());

}

}
}

最佳答案

似乎 current = current.leftChild; 永远不会在递归步骤中使用,因为 current = this 会将 current 设置为树的顶部。因此,您可能希望将其添加为参数并首先传递 this

对于返回,您可以将其设置为整数数组,例如 int[]ArrayList。它们可以保存多个值。

关于java - BST 最小 n 个元素显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51711495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com