Find all nodes in a binary tree on a specific level (Interview Query)

落花浮王杯 提交于 2020-01-11 03:31:05

问题


I mean on a specific level, NOT up to that specific level. Could someone please check my modified BFS algorithm? (most of which is taken from Wikipedia)

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

回答1:


I think a recursive solution would be much more concise:

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

Initial invocation would look like: drill (root, 0, n, rqueue);




回答2:


The problem with your algorithm is that nodes that are all at same level are wrongly increasing the level count.

Explanation :

  1. Set level of the root to be 0

  2. As you add nodes at any level, set their level to be 1 more than level of their parent.

  3. Once you get any node that has the level number equal to the level number you require, simple break out of BFS, and dump all the nodes in the queue behind the current node that have same level number.

Please see the comment for details.

Here is one solution :

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

Here is some sample output :

      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  

If you are interested, i have added the function to my generic trees implementation here. You'll find a large number of tree operations for reference (mirror, height, pretty printing etc).



来源:https://stackoverflow.com/questions/13349853/find-all-nodes-in-a-binary-tree-on-a-specific-level-interview-query

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