0

I have this method and it should show on the screen the smallest n Elements in BST, Example n=3, the smallest 3 elements and so on..

Unfortunately at running, it shows that its reaching an Empty content and gets shut down. Further notes, the method should give and int back and its not void, but I couldn't find another way to show all the Elements, because return type int will give just one Element? right?

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());

        }

    }
}
gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
Fadi41
  • 3
  • 4
  • This method won't even compile because there is no return statement in the case that `n<=0` or `isEmpty()` evaluates true. – Roddy of the Frozen Peas Aug 06 '18 at 16:07
  • You can have a look at this question: [In-order iterator for binary tree](https://stackoverflow.com/questions/12850889/in-order-iterator-for-binary-tree). Once you have the iterator, it should be easy to find the first `n` elements, and return them in a list. – Malte Hartwig Aug 06 '18 at 16:08
  • ah sorry i forgot to write the return here , it does compile – Fadi41 Aug 06 '18 at 16:24
  • Iam not allowed to use an iterator – Fadi41 Aug 06 '18 at 16:25

1 Answers1

1

It seems that the current = current.leftChild; will never get used in the recursive step because current = this will set current to the top of the tree. So you might want add that as parameter and initially pass this.

For the return, you can make it as array of integers like int[] or an ArrayList. Those can hold more than one values.

Magdrop
  • 568
  • 3
  • 13