简体   繁体   中英

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

Use of while in the function is wrong. It needs to be if . Otherwise, the function never breaks out of the while loop.

FWIW, that function can be simplified to:

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

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

Couple of Things here.

From the code as i understand, you are trying to print in a pre-order fashion. the While Loop is unnecessary and that is what is causing the infinite loop Lets say you have two nodes root and root->left your function will print root, call the function recursively on root' = root->right (will not print anything this time because root'->left is NULL and root'->right is NULL). Then the function print(root') returns to its caller which is print(root). This time it will not exit out of the while Loop because the while condition is always true, ergo the infinite Loop.

you can simply do this

Print(root)
    cout << root;
    if(root->right != NULL)
        Print(root->right);
    if(root->left != NULL)
        Print(root->left);

TO display "No Movies" just check if root == NULL before calling this recursive function Print(root);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM