我的意思是在特定级别,而不是达到特定级别。有人可以检查一下我修改过的BFS算法吗? (大部分来自维基百科)
Queue levelorder(root, levelRequested){
int currentLevel = 0;
q = empty queue
q.enqueue(root)
while not q.empty do{
if(currentLevel==levelRequested)
return q;
node := q.dequeue()
visit(node)
if(node.left!=null || node.right!=null){
currentLevel++;
if node.left ≠ null
q.enqueue(node.left)
if node.right ≠ null
q.enqueue(node.right)
}
}
}
答案 0 :(得分:22)
我认为递归解决方案会更加简洁:
/*
* node - node being visited
* clevel - current level
* rlevel - requested level
* result - result queue
*/
drill (node, clevel, rlevel, result) {
if (clevel == rlevel) {
result.enqueue (node);
else {
if (node.left != null)
drill (node.left, clevel + 1, rlevel, result);
if (node.right != null)
drill (node.right, clevel + 1, rlevel, result);
}
}
初始调用如下:drill (root, 0, n, rqueue);
答案 1 :(得分:3)
您的算法存在的问题是,所有处于同一级别的节点都会错误地增加级别计数。
说明:
将根级别设置为0
在任何级别添加节点时,请将其级别设置为比其父级别高1级。
一旦获得任何级别等于所需级别号的节点,就可以简单地中断BFS,并将当前节点后面队列中所有节点转储到具有相同级别编号的队列中。
请参阅评论了解详情。
这是一个解决方案:
void Tree::printSameLevel(int requiredLevel) {
queue BFSQ;
TreeNode * temp;
BFSQ.push(getHead());
while(!BFSQ.empty()) {
temp = BFSQ.front();
BFSQ.pop();
//if the level of the current node is equal to the
//required level, we can stop processing now and simply
//remove from the queue all the elements that follow
//and have the same level number.
//It follows from properties of BFS that such elements
//will occur in a series ( level by level traversal).
if(temp->level == requiredLevel) {
break;
}
if(temp->right) {
BFSQ.push(temp->right);
temp->right->level = temp->level + 1;
}
if(temp->left) {
BFSQ.push(temp->left);
temp->left->level = temp->level + 1;
}
}
if(!BFSQ.empty() || requiredLevel==0) {
cout << "Printing all the nodes at level " << requiredLevel << " : ";
while(temp&&temp->level == requiredLevel) {
cout << temp->data << " ";
temp = BFSQ.front();
BFSQ.pop();
}
}
}
以下是一些示例输出:
5
7 3
8 6 4 2
TREE STATS
_____________________
Inorder Trace = 2 3 4 5 6 7 8
Height = 2
Internal Nodes = 3
Leaf Nodes = 4
Total Nodes = 7
_____________________
Trees printed above are mirrors!
Printing all the nodes at level 0 : 5
Printing all the nodes at level 1 : 7 3
如果您有兴趣,我已将该功能添加到我的通用树实现here。您将找到大量的树操作供参考(镜像,高度,漂亮打印等)。