简体   繁体   中英

In-order traversal of an AVL tree, saving the values in an array

I am trying to iterate through an AVL tree inorder (from minimum value to maximum value), and save the values in an array. How can I do such a thing? I am stuck in this recursion and can't figure how to do it correctly, here is what I have so far:

// Called with node = root node of the AVL tree
// x is the length of the array
// y is 0 at the start
// array is the array I want to fill

void inorder(int* array,Tree_Node* node,int x,int y)
{
    if(!node)
    {
        return;
    }
    inorder(array, node->getLeft(), x, y);

    array[y] = GET_ID(node->getkey());
    y++;
    if (y == x)
    {
        return;
    }
    inorder(array, node->getRight(), x, y);
} 

The big issue here is that your array indexing is wrong. Consider the in-order-traversal of an arbitrary node. You write everything under the left child starting from index y . Then you ignore what you just did, and write the current node's value at index y . Then, because you always increment y , it is possible that y > x at the point you check for y == x , and you write out-of-bounds.

I would highly recommend solving this with an std::vector (whose data() member function can be used just like an array if you need that for further processing). That would also allow you to get rid of the length limitation:

void inorder(Tree_Node* node, std::vector<int>& vector)
{
    if (!node) return;
    inorder(node->getLeft(), vector);

    vector.push_back(GET_ID(node->getkey()));

    inorder(node->getRight(), vector);
}

However, if you have to use arrays (because manually implementing AVL trees is often done in education and some educators are crazy enough to demand that you don't use all the features available to you), you can still fix this by returning the current array index from the function:

int inorder(int* array, Tree_Node* node, int size, int y = 0)
{
    if (!node) return y;
    y = inorder(array, node->getLeft(), size, y);

    if (y >= size) return y; /* Check before you write! */
    array[y++] = GET_ID(node->getkey());

    return inorder(array, node->getRight(), size, y);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM