Cum pot crea copac?

voturi
1

Am încercat să fac o BST și trebuie să-l imprima inordine, postordine și precomandă.

Lucrul nu sunt sigur cu privire la modul în care este de a crea acest copac în mea main()funcție.

struct Tree_Node
{
    Tree_Node *right;
    Tree_Node *left;
    int info;
};

class bTree
{
private:
    Tree_Node *root;
public:
    bTree();
    void bTree::Insert(Tree_Node*& tree, int item);
    void bTree::preorderPrint(Tree_Node *root);
};

bTree::bTree()
{
    root = NULL;
}


void bTree::Insert(Tree_Node*& tree, int item)
{
  if (tree == NULL)
  {
    tree = new Tree_Node;
    tree->right = NULL;
    tree->left = NULL;
    tree->info = item;
  }
  else if (item < tree->info)
    Insert(tree->left, item);    
  else
    Insert(tree->right, item);   
} 

void bTree::preorderPrint(Tree_Node *root)
{
    if ( root != NULL ) 
    {
        cout << root->info <<  ;
        preorderPrint( root->left );   
        preorderPrint( root->right );   
    }
}

void main()
{
// This is where I need help at
// I'm not sure how to insert a new node

    bTree Test;
    Test.Insert(    
}
Întrebat 08/12/2009 la 07:27
sursa de către utilizator
În alte limbi...                            


2 răspunsuri

voturi
2

Prin aspectul de lucruri, puteți scrie doar

Test.Insert(Test.root, 3); // Insert 3
Test.Insert(Test.root, 4); // Insert 4

și că ar trebui să funcționeze. Desigur, va trebui să facă publice rădăcină.

Cu toate acestea, acest lucru este un pic ciudat, deoarece primul parametru va fi întotdeauna bTree.root - și nu trebuie să facă publică. Amintiți - vă că utilizatorul de tipul de date (sau altcineva) nu ar trebui să aibă grijă de noduri , cum ar fi componente interne - le pasa doar cu privire la datele lor. În schimb, aș recomanda a face o comoditate Insertmetodă care are nevoie doar să ia un număr întreg (nu un nod copac) - aceasta se numește Supraîncărcarea.

void bTree::Insert(int item)
{
    Insert(root, item);
}

// Keep the other insert method, but make it private.

Apoi, puteți scrie doar:

Test.Insert(3);
Test.Insert(4);
Publicat 08/12/2009 la 07:37
sursa de către utilizator

voturi
1
void bTree::Insert(int item)
{
  Tree_Node * node = new Tree_Node;
  node->left = NULL;
  node->right = NULL;
  node->info = item;
  if (root == NULL)
  {
    root = node;
    return;
  }
  Tree_Node * t = root;
  Tree_Node * p = root;
  while(1)
  {
    if (item < t->info)
    {
       t = t->left;
       if(t == NULL)
       {
          p->left = node;
          return;
       }
    }
    else if(item > t->info)
    {
       t = t->right;
       if(t == NULL)
       {
          p->right = node;
          return;
       }
    }
    else //item already exists in the tree
       return;
    p = t;
  }

} 

//now you can insert nodes like
Test.Insert(5);
Test.Insert(6);
Publicat 08/12/2009 la 07:46
sursa de către utilizator

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more