How to traverse a Btree?

浪尽此生 提交于 2021-01-28 06:27:17

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2799966/how-to-traverse-a-btree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!