BST level bypass

Ok so I'm trying to do a binary search tree level traversal and its not working. The code below makes sense to me, but that's probably because I've looked at it forever and I 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); 
 } 
}

      

Perhaps you guys can point out what I am doing wrong, because while I understand the concept of a binary search tree, I am not 100% on all the ins and outs.

+2


a source to share


1 answer


As a result, nothing happens.

Can you explain how you get to 24,12,18?

I assume you insert 12 first at the root level, then insert 24 that ends as a right node from root 12, then you insert 18 that ends as a left node of 24 - because 18 is greater than root 12 so to the right, then 18 less than 24 so it is inserted as the 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 bypassing level 12,24,18 as you add your algorithm.

+1


a source







All Articles