Fadi41
Fadi41

Reputation: 3

BST smallest n elements show

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

        }

    }
}

Upvotes: 0

Views: 44

Answers (1)

Magdrop
Magdrop

Reputation: 578

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.

Upvotes: 1

Related Questions