c++traversaladts

BST Level Traversal


Ok, so I'm trying to do a level order traversal of a binary search tree and its not working. The code below makes sense to me, but that is probably because I've been looking at it forever and I've convinced myself that it should work.

void BST<T>::levelByLevel(ostream &out) { 
 Queue<BinNodePointer> q; 
 BinNodePointer subtreeRoot; 

 if(myRoot == NULL) 
  return; 
 q.enqueue(myRoot); 
 while(!q.empty()) {
  subtreeRoot = q.front(); 
  out << subtreeRoot->data << " "; 
  q.dequeue(); 

  if(subtreeRoot->left != NULL) 
   q.enqueue(subtreeRoot->left); 
  if(subtreeRoot->right != NULL) 
   q.enqueue(subtreeRoot->right); 
 } 
}

Maybe you guys could point out what I'm doing wrong because, although I understand the concept of a binary search tree, I'm not 100% on all the ins and outs.


Solution

  • There is nothing wrong with the result.

    Can you explain how do you arrive at 24,12,18 ?

    I assume you insert 12 first at root level, then you insert 24 which ends up as right node of root 12 then you insert 18 which ends up as left node of 24 - because 18 is bigger then root 12 so going right, then 18 is less then 24 so it is inserted as right node of 24

    So:

    12
    
    
    12
      \
      24
    
    12
      \
      24
     /
    18
    

    So you have 3 levels, level 1 (12), level 2 (24), level 3 (18) so level traversal 12,24,18 as your algorithm is inserting.