0

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;
        }
1
  • You are not allowed to use global variables or local function variables? Commented May 4, 2017 at 20:38

1 Answer 1

2

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.