问题
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