我正在写一个B树的symulator。 我在这里阅读stackoverflow,最好的方法是使用队列进行级别顺序遍历。但我不知道该怎么做。 我从geeksforgeeks开始用c ++实现。 也许有人知道如何重建inorder遍历(下面的代码)到级别顺序遍历。
类和构造函数:
sonar-runner
顺序遍历:
class BTreeNode
{
int *keys; // An array of keys
int t; // Minimum degree (defines the range for number of keys)
BTreeNode **C; // An array of child pointers
int n; // Current number of keys
int j;
bool leaf; // Is true when node is leaf. Otherwise false
public:
BTreeNode(int _t, bool _leaf); // Constructor
// A utility function to insert a new key in the subtree rooted with
// this node. The assumption is, the node must be non-full when this
// function is called
void insertNonFull(int k);
// A utility function to split the child y of this node. i is index of y in
// child array C[]. The Child y must be full when this function is called
void splitChild(int i, BTreeNode *y);
// A function to traverse all nodes in a subtree rooted with this node
void traverse();
// A function to search a key in subtree rooted with this node.
BTreeNode *search(int k); // returns NULL if k is not present.
// Make BTree friend of this so that we can access private members of this
// class in BTree functions
friend class BTree;
};
// A BTree
class BTree
{
BTreeNode *root; // Pointer to root node
int t; // Minimum degree
public:
// Constructor (Initializes tree as empty)
BTree(int _t)
{ root = NULL; t = _t; }
// function to traverse the tree
void traverse()
{ if (root != NULL)
cout << "root";
root->traverse(); }
// function to search a key in this tree
BTreeNode* search(int k)
{ return (root == NULL)? NULL : root->search(k); }
// The main function that inserts a new key in this B-Tree
void insert(int k);
};
答案 0 :(得分:0)
在这里,您可以看到Depth-First-Search算法(wiki)的递归实现 对于逐级遍历,您可能需要广度优先搜索(wiki)。
为实现这一目标,我们将执行两个步骤 第一步:编写无递归DFS:
void BTreeNode::traverse()
{
std::stack<BTreeNode*> stack;
stack.push(this);
while (!stack.empty())
{
BTreeNode* current = stack.top();
stack.pop();
int i;
for (i = 0; i < n; i++)
{
if (leaf == false)
stack.push(current->C[i]);
cout << " " << current->keys[i];
}
if (leaf == false)
stack.push(current->C[i]);
}
}
第二步:使用队列而不是堆栈:
void BTreeNode::traverse()
{
std::queue<BTreeNode*> queue;
queue.push(this);
while (!stack.empty())
{
BTreeNode* current = queue.front();
queue.pop();
int i;
for (i = 0; i < n; i++)
{
if (leaf == false)
stack.push(current->C[i]);
cout << " " << current->keys[i];
}
if (leaf == false)
stack.push(current->C[i]);
}
}
所以,它已经完成了!