Search code examples
c++g++traversalb-treetree-traversal

How to traverse a Btree?


I have a Btree and I'm trying to figure out how traverse it so that the keys are displayed ascending order.

All I can figure out is that this can be done with a recursive function.

What's the pseudo-code to do it?


Solution

  • Assuming you have a definition like:

    template <class T>
    class btree_node
    {
        btree_node **child;  // an array of child nodes
        T **element;  // the elements in this node
    
        unsigned int child_count; // the number of children
                                  // the number of elements is 1 less then child_count
    };
    

    Then you'll need do something like this:

    void btree_inorder(node):
        for (int i = 0; i < node.child_count; ++i)
        {
            btree_inorder(node.child[i]);
            handle_element(node.element[i]);
        }
        btree_inorder(node.child[node.child_count-1]);