Search code examples
javarecursionred-black-tree

Set limit to the number of recursive calls - Java


I have a class of a Red-Black Tree.

I want to print it in-order (so the numbers would be printed from smallest to laregst).

Here's the printing method:

public void printTreeInOrder(Node node){
        //in-order printing (sorted)
        if (!(isNull(node))){
            printTreeInOrder((node.getLeft()));
            System.out.println(node.getValue());
            printTreeInOrder(node.getRight());
        }
    }

However I want to print only the k smallest numbers. It would be easy if I could limit the number of recursive calls, such as holding a sentinal and count the number of times the method is called.

But how do I it in a recursive function?

I thought of making a global variable k and count it in the function, but it doesn't sound right, and k is a variable itself, it is not constant. I there a way I could count the amount of numbers printed in a recursive function?

Thanks,

Alan


Solution

  • The method returns the number of elements remaining to be printed and accepts the maximum number of elements that can be printed from this node.

    public int printTreeInOrder(Node node, int k){
        //in-order printing (sorted)
        if (k>0 && !(isNull(node))){
            k = printTreeInOrder(node.getLeft(),k);
            if (k>0) {
                System.out.println(node.getValue());
                k--;
            }
            return printTreeInOrder(node.getRight(),k);
        }
        return k;
    }