Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java BST最小n个元素显示_Java_Binary Search Tree - Fatal编程技术网

Java BST最小n个元素显示

Java BST最小n个元素显示,java,binary-search-tree,Java,Binary Search Tree,我有这个方法,它应该在屏幕上显示BST中最小的n个元素, 示例n=3,最小的3个元素,依此类推 不幸的是,在运行时,它显示它到达了一个空内容并被关闭。进一步注意,该方法应该返回give和int,而不是void,但是我找不到另一种方法来显示所有元素,因为返回类型int只会给出一个元素?对吧? public int sorteduptp(int n) { if (n > 0 && !isEmpty()) { BinarySearchTree curren

我有这个方法,它应该在屏幕上显示BST中最小的n个元素, 示例n=3,最小的3个元素,依此类推

不幸的是,在运行时,它显示它到达了一个空内容并被关闭。进一步注意,该方法应该返回give和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=此
会将current设置为树的顶部。因此,您可能希望将其添加为参数,并在最初传递


对于返回,可以将其设置为整数数组,如
int[]
ArrayList
。这些值可以包含多个值。

此方法甚至不会编译,因为在
的情况下没有返回语句,您可以查看以下问题:。一旦你有了迭代器,应该很容易找到第一个
n
元素,并将它们返回到一个列表中。啊,对不起,我忘了在这里写返回,它不会编译。我不允许使用迭代器