hypr2
hypr2

Reputation: 43

Recursive call without global variables or function parameters

So we got a homework to count nodes in binary search tree but we are not allowed to use global variables or function parameters since we get a pre made template which we shouldn't change. I know how to do that with global variable and function parameter, but I don't know how to do that without it since I can't use local variable.

My code now:

int count() const
        {
            int st = 1;
            if (left != NULL) {
                st++;
                left->count();
            }
            if (right != NULL) {
                st++;
                right->count();
            }
            return st;
        }

Upvotes: 0

Views: 1095

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

You could just sum up the return-values provided by recursive calls to the respective sub-trees (if available):

    int count() const
    {
        if (left != NULL && right != NULL)
           return 1+left->count()+right->count();
        else if (left != NULL)
           return 1+left->count();
        else if (right != NULL)
           return 1+right->count();
        else
           return 1;
    }

Upvotes: 2

Related Questions