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
2009-12-02 00:11:27
how do i know when to visit right child in my situation?
Corey
2009-12-02 00:13:49
Visit either child if it exists. See updated answer.
caf
2009-12-02 00:19:35
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
2009-12-02 00:27:03
Probably because `size <= 17`, so you may have an off-by-one error in your insert function.
caf
2009-12-02 00:37:22
Corey
2009-12-02 00:54:04
I guess we can use same code for post order and in order traversals with little modifications. Isn't it true?
atv
2009-12-02 21:17:41
Sure, it's trivial to modify that to post-order or in-order - just a rearrangement of the statements.
caf
2009-12-02 22:45:57
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
2009-12-02 00:16:31
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
2009-12-02 00:26:45
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
2009-12-02 00:28:36
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
2009-12-02 00:23:48