Whatamia Whatamia - 1 month ago 23
C++ Question

printing the contents of a Binary Search Tree recursively?

void MovieTree::printMovieInventory(MovieNode* node)
{
if(node)
{
while(node->rightChild!=NULL or node->leftChild!=NULL)
{
std::cout<<"Movie:"<<node->title<<" "<<node->quantity<<std::endl;
if(node->rightChild)
{
printMovieInventory(node->rightChild);
}
if(node->leftChild)
{
printMovieInventory(node->leftChild);

}
}
}
else
{
std::cout<<"No movies in list!"<<std::endl;
}
}


I'm not sure if this function is causing my issue or if it's my adding function but I feel as though the logic to this is correct. Am I missing something?

Edit::
My issue is that it's resulting in an infinite loop and it's not properly printing all associated children of the tree

Answer

In addition to the problem with the while loop, this can also never print leaf nodes, as you don't print the node itself if it doesn't have either a left or a right child.

while(node->rightChild!=NULL or node->leftChild!=NULL)
        {
            std::cout<<"Movie:"<<node->title<<" "<<node->quantity<<std::endl;

it should be

if(node)
    print node
    if left
       recurse left
    if right
        recurse right