4

我的意思是在特定级别上,而不是在特定级别上。有人可以检查我修改后的 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)
           }
      }
}
4

2 回答 2

23

我认为递归解决方案会更简洁:

/*
 * 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);

于 2012-11-12T19:44:51.890 回答
3

您的算法的问题是所有处于同一级别的节点错误地增加了级别计数。

解释 :

  1. 将根的级别设置为0

  2. 在任何级别添加节点时,请将其级别设置为比其父级高 1。

  3. 一旦你得到任何级别号等于你需要的级别号的节点,简单地跳出 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  

如果您有兴趣,我已在此处将函数添加到我的通用树实现中。你会发现大量的树操作供参考(镜子、高度、漂亮的打印等)。

于 2012-11-12T20:06:44.597 回答