+ Reply to Thread
Results 1 to 2 of 2

Thread: Specialne vypisovanie binarneho stromu v C++

  1. #1

    Specialne vypisovanie binarneho stromu v C++

    Zdravom ludia, mam dost velky problem. Mam takuto ulohu:

    Naplnte nahodne (aj lub. pocet vrcholov) binarny strom a vypiste ho:

    v tvare: 3body

    Priklad:

    5
    3 10
    1 4 6 11

    Vytovoril som stromcek a a nahodne som si ho naplnil. Moj problem je v metode print(). Neviem ako vypisat dany strom v takejte podobe ako je v zadani. Tu je moj kod ktory mam uz pripraveny.

    Code:
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    class Item
    {
     public:
            int value;
            Item* right;
            Item* left;
    
            Item(int value)
            {
              right = NULL;
              left = NULL;
              this->value = value;
            }
    };
    
    class Tree
    {
     public:
            Item* root;
    
            Tree(int val)
            {
              this->root = new Item(val);
            }
    
            void add(int val)
            {
             if(root == NULL)
             {
              root = new Item(val);
              return;
             }
             Item* ac = root;
             Item* pr = root;
    
             while(1)
             {
               if(val < ac->value)
               {
                 pr = ac;
                 ac = ac->left;
    
                 if(ac == NULL)
                 {
                   ac = new Item(val);
                   pr->left = ac;
                   return;
                 }
                }
                else
                {
                  pr = ac;
                  ac = ac->right;
                  if(ac == NULL)
                  {
                    ac = new Item(val);
                    pr->right = ac;
                    return;
                  }
                }
               }
              }
    
              void print(Item* root)
              {
                if(root->left != NULL)
                {
                  print(root->left);
                }
                cout<<root->value<<" "<<endl;
                
                if(root->right != NULL)
                {
                  print(root->right);
                 } 
              }
    };
    
    int main()
    {
     Tree a(5);
     int i;
     
     for(i = 0; i < rand() % 20; i++)
     {
           a.add(rand() % 100);
     }
     
     a.print(a.root);
     
     system("pause"); 
     return 0;
    }
    Prosim hori mi termin.
    Všetko o hrách a novinkách s herného sveta nájdete na http://the-guild.cz/.

  2. #2

+ Reply to Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts