BST Level Traversal

Posted by Dalton Conley on Stack Overflow See other posts from Stack Overflow or by Dalton Conley
Published on 2010-05-02T22:55:37Z Indexed on 2010/05/02 22:57 UTC
Read the original article Hit count: 172

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about adts