views:

327

answers:

3

I am trying to do a preorder traverse

+1  A: 

Preorder traversal just means the "visit" function looks like:

  • process contents of this node;
  • visit left child;
  • visit right child;

Addendum:

It's not entirely clear from your code, but you might try something like this:

void BST::displayPreOrder(std::ostream &out, int parent)
{
    if (parent < size) 
    {
        if (!items[parent].empty)
        {
            out << items[parent].instanceData;
            out << endl;
        }

        this->displayPreOrder(out, 2 * parent + 1);   
        this->displayPreOrder(out, 2 * parent + 2);   
    }
}

(If "empty" nodes never have any child nodes, then you can combine that into a single if statement).

caf
how do i know when to visit right child in my situation?
Corey
Visit either child if it exists. See updated answer.
caf
Well, it appears that your nodes can exist (`index < size`) but still be empty (`items[index].empty == true`). You have to visit child nodes if they *exist*, but only print node contents if the node is *non-empty*.
caf
Probably because `size <= 17`, so you may have an off-by-one error in your insert function.
caf
Corey
I guess we can use same code for post order and in order traversals with little modifications. Isn't it true?
atv
Sure, it's trivial to modify that to post-order or in-order - just a rearrangement of the statements.
caf
A: 

Here is some psuedo code of a preorder that may help.

void Preorder( out, int parent )
{
    out << items[parent];
    left = parent * 2 + 1;
    right = parent * 2 + 2;

    if( left> -1 )
        Preorder( out, left );

    if( right > -1 )
        Preorder( out, right );
}
BioBuckyBall
Nothing wrong with many small functions. But the main reason I did that is that I forget the formulas for the left and right children when storing a bst in an array and was too lazy to find the wiki page. :D
BioBuckyBall
oh, and no, you wouldn't need additional left/right functions for the other traversals. The locations of left and right children are independent of the traversal type.
BioBuckyBall
A: 

Your function for visiting nodes only goes left or right. Try something more like this:

void BST::displayPreOrder(std::ostream &out, int parent)const
{    
   if (parent>=0 && parent<size && !items[parent].empty) 
   {
       out << items[parent].instanceData;
       out << endl;

       if (true )
       {
            // go left
            int next = (2 * parent)+ 1; 
            this->displayPreOrder(out,next);    
       }

       if( true )
       {
           // go right
           int next = (2 * parent)+ 2; 
           this->displayPreOrder(out,next);
       }
    }
}

The calculations I show for 'next' may or may not be right ... you haven't given us a full description of how you're embedding this tree in the array, so I can only guess based on what you did show us.

Eric