I have an algorithm for a recursive tree traversal. It's job is to traverse a tree adding up all the number values stored inside the tree. The tree stores, integers, doubles, strings, and tree's themselves as data members. So node's containing strings and tree's are just skipped, but other nodes are summed together to find out the total of all the values in the tree (not including other values inside a tree as a data value). There is a stub method inside the tree class that calls the actual method inside the Node class to do the work. Unfortunately i get a bogus number returned. Any ideas???
Code:
double Node::total()
{
double result;
IntTreeItem *x;
FloatTreeItem *y;
if( this->getLeft() != NULL )
{
if( typeid( this->getLeft()->getValue() ).name() == typeid( x ).name() || typeid( this->getLeft()->getValue() ).name() == typeid( y ).name() )
result += this->getLeft()->total(); //it gets added
else
this->getLeft()->total(); //it isn't the right type, skip it
}
//this is where the value gets calculated
if( typeid( this->getValue() ).name() == typeid( x ).name() )
{
result += (double)( ( dynamic_cast<IntTreeItem*>( this->getValue() ) )->getValue() ); //cast TreeItem down to IntTreeItem, envoke it's value method, then convert to double
}
else if( typeid( this->getValue() ).name() == typeid( y ).name() )
{
result += ( ( dynamic_cast<FloatTreeItem*>( this->getValue() ) )->getValue() ); //cast TreeItem down to FloatTreeItem, envoke it's value method (which gives a double)
}
if( this->getRight() != NULL )
{
if( typeid( this->getLeft()->getValue() ).name() == typeid( x ).name() || typeid( this->getLeft()->getValue() ).name() == typeid( y ).name() )
result += this->getLeft()->total(); //it gets added
else
this->getLeft()->total(); //wrong type, it doesn't get added
}
return result;
}