Neil Munroe
Neil Munroe

Reputation: 45

Using tree sort to modify array

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.

Upvotes: 2

Views: 283

Answers (1)

dieram3
dieram3

Reputation: 591

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

Upvotes: 3

Related Questions