W jaki sposób można utworzyć drzewo?

głosy
1

Próbuję zrobić BST i trzeba go wydrukować Inorder, postorder i przedsprzedaży.

Rzecz nie jestem pewien, o to, jak stworzyć tego drzewa w mojej main()funkcji.

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(    
}
Utwórz 08/12/2009 o 07:27
źródło użytkownik
W innych językach...                            


2 odpowiedzi

głosy
2

Przez spojrzeń rzeczy, można po prostu napisać

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

i że powinno działać. Oczywiście, będziesz musiał dokonać główny publicznej.

Jednak jest to trochę niewygodne, ponieważ pierwszy parametr zawsze będzie bTree.root - i nie trzeba, aby to do wiadomości publicznej. Pamiętaj, że użytkownik danego typu danych (Ty lub ktokolwiek inny) nie powinien się przejmować wewnętrznych, takich jak węzły - dbają tylko o swoje dane. Zamiast tego, polecam dokonywania ogólnospożywczy Insertmetodę, która dopiero musi brać całkowitą (nie węzeł drzewa) - nazywa się to przeciążenie.

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

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

Następnie można po prostu napisać:

Test.Insert(3);
Test.Insert(4);
Odpowiedział 08/12/2009 o 07:37
źródło użytkownik

głosy
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);
Odpowiedział 08/12/2009 o 07:46
źródło użytkownik

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