2

I am looking to use tree sort in order to store the numbers sorted in an array as opposed to just outputting the numbers in a sorted order. n is initialized to zero.

void BinSearchTree::inOrder( TreeNodePtr subRoot, int A[], int n )
{
    if ( subRoot != NULL )             
    {
        inOrder( subRoot->left, A, n );    

        A[n] = subRoot->key;
        n++;

        inOrder( subRoot->right, A, n ); 
    }
}

I believe the problem lies where I continue to call A as a parameter for inOrder but I don't know how else I would do this.

1 Answer 1

3

You should have a reference to n, otherwise you can't know what is the next element to assign, that is:

void BinSearchTree::inOrder( TreeNodePtr subRoot, int A[], int& last )
{
    if ( subRoot != NULL )             
    {
        inOrder( subRoot->left, A, n );    

        A[last++] = subRoot->key;

        inOrder( subRoot->right, A, n ); 
    }
}

Other option would be to use a container with a push_back function like a vector:

 void BinSearchTree::inOrder( TreeNodePtr subRoot, std::vector<int>& vec )
    {
        if ( subRoot != NULL )             
        {
            inOrder( subRoot->left, vec );    

            vec.push_back( subRoot->key );

            inOrder( subRoot->right, vec); 
        }
    }
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.