1

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?

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
neuromancer
  • 53,769
  • 78
  • 166
  • 223

2 Answers2

2

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]);
R Samuel Klatchko
  • 74,869
  • 16
  • 134
  • 187
1
void traversalBtree(struct node * root){
    int i = 1;
    if(root != NULL){
        while(i <= root->n){
            if(root->leaf == 0)
                traversalBtree(root->link[i]);
            printf("\t%d", root->key[i]);
            i++;
        }
        if(root->leaf == 0)
            traversalBtree(root->link[i]);
    }
}
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
Anup Patel
  • 11
  • 1