2015-05-19 2 views
0

Здравствуйте, я пишу avl-дерево, и у меня есть одна проблема. В настоящее время у меня есть корень как глобальный, поскольку я использую его как в классе, так и в основном, как я могу написать его, не имея его глобального?Я хотел бы не использовать root как глобальный

struct avl_node { 
    int data; 
    struct avl_node *left; 
    struct avl_node *right; 
}*root; 

class avlTree { 
    public: 
     int height(avl_node *temp) 
     { 
      int h = 0; 
      if (temp != NULL) 
      { 
       int l_height = height (temp->left); 
       int r_height = height (temp->right); 
       int max_height = max (l_height, r_height); 
       h = max_height + 1; 
      } 
      return h; 
     } 

     int diff(avl_node *temp) 
     { 
      int l_height = height (temp->left); 
      int r_height = height (temp->right); 
      int b_factor= l_height - r_height; 
      return b_factor; 
     } 

     avl_node *rr_rotation(avl_node *parent) 
     { 
      avl_node *temp; 
      temp = parent->right; 
      parent->right = temp->left; 
      temp->left = parent; 
      return temp; 
     }  

     avl_node *ll_rotation(avl_node *parent) 
     { 
      avl_node *temp; 
      temp = parent->left; 
      parent->left = temp->right; 
      temp->right = parent; 
      return temp; 
     } 

     avl_node *lr_rotation(avl_node *parent) 
     { 
      avl_node *temp; 
      temp = parent->left; 
      parent->left = rr_rotation (temp); 
      return ll_rotation (parent); 
     } 

     avl_node *rl_rotation(avl_node *parent) 
     { 
      avl_node *temp; 
      temp = parent->right; 
      parent->right = ll_rotation (temp); 
      return rr_rotation (parent); 
     } 

     avl_node* balance(avl_node *temp) 
     { 
      int bal_factor = diff (temp); 
      if (bal_factor > 1) 
      { 
       if (diff (temp->left) > 0) 
        temp = ll_rotation (temp); 
       else 
        temp = lr_rotation (temp); 
      } 
      else if (bal_factor < -1) 
      { 
       if (diff (temp->right) > 0) 
        temp = rl_rotation (temp); 
       else 
        temp = rr_rotation (temp); 
      } 
      return temp; 
     } 

     avl_node* insert(avl_node *root, int value) 
     { 
      if (root == NULL) 
      { 
       root = new avl_node; 
       root->data = value; 
       root->left = NULL; 
       root->right = NULL; 
       return root; 
      } 
      else if (value < root->data) 
      { 
       root->left = insert(root->left, value); 
       root = balance (root); 
      } 
      else if (value >= root->data) 
      { 
       root->right = insert(root->right, value); 
       root = balance (root); 
      } 
      return root; 
     } 

     void display(avl_node *ptr, int level) 
     { 
      int i; 
      if (ptr!=NULL) 
      { 
       display(ptr->right, level + 1); 
       printf("\n"); 
       if (ptr == root) 
        cout<<"Root -> "; 
       for (i = 0; i < level && ptr != root; i++) 
        cout<<"  "; 
       cout<<ptr->data; 
       display(ptr->left, level + 1); 
      } 
     } 

     void inorder(avl_node *tree) 
     { 
      if (tree == NULL) 
       return; 
      inorder (tree->left); 
      cout<<tree->data<<" "; 
      inorder (tree->right); 
     } 

     void preorder(avl_node *tree) 
     { 
      if (tree == NULL) 
       return; 
      cout<<tree->data<<" "; 
      preorder (tree->left); 
      preorder (tree->right); 
     } 

     void postorder(avl_node *tree) 
     { 
      if (tree == NULL) 
       return; 
      postorder (tree ->left); 
      postorder (tree ->right); 
      cout<<tree->data<<" "; 
     } 

     avlTree() 
     { 
      root = NULL; 
     } 
}; 


int main() 
{ 
    int choice, item; 
    avlTree avl; 
    while (1) 
    { 
     cout<<"\n---------------------"<<endl; 
     cout<<"AVL Tree Implementation"<<endl; 
     cout<<"\n---------------------"<<endl; 
     cout<<"1.Insert Element into the tree"<<endl; 
     cout<<"2.Display Balanced AVL Tree"<<endl; 
     cout<<"3.InOrder traversal"<<endl; 
     cout<<"4.PreOrder traversal"<<endl; 
     cout<<"5.PostOrder traversal"<<endl; 
     cout<<"6.Exit"<<endl; 
     cout<<"Enter your Choice: "; 
     cin>>choice; 
     switch(choice) 
     { 
      case 1: 
       system("cls"); 
       cout<<"Enter value to be inserted: "; 
       cin>>item; 
       root = avl.insert(root, item); 
       break; 
      case 2: 
       system("cls"); 
       if (root == NULL) 
       { 
        cout<<"Tree is Empty"<<endl; 
        continue; 
       } 
       cout<<"Balanced AVL Tree:"<<endl; 
       avl.display(root, 1); 
       break; 
      case 3: 
       system("cls"); 
       cout<<"Inorder Traversal:"<<endl; 
       avl.inorder(root); 
       cout<<endl; 
       break; 
      case 4: 
       system("cls"); 
       cout<<"Preorder Traversal:"<<endl; 
       avl.preorder(root); 
       cout<<endl; 
       break; 
      case 5: 
       system("cls"); 
       cout<<"Postorder Traversal:"<<endl; 
       avl.postorder(root);  
       cout<<endl; 
       break; 
      case 6: 
       exit(1);  
       break; 
      default: 
       system("cls"); 
       cout<<"Wrong Choice"<<endl; 
     } 
    } 
    return 0; 
} 
+0

Почему 'root' является узлом, а не' avlTree' (который должен содержать корневой узел)? Тогда большинство из этих функций работают с содержащимся «root», а не с параметром. – crashmstr

+0

Я понимаю, что вы имеете в виду, но я довольно не знаю, как его реализовать. – Bogdan

+0

Сделайте 'root' членом класса:' class avlTree {struct avl_node {...} * root; public: ... methods}; ' – CiaPan

ответ

0

Вы не должны явно использовать root в main(), и вообще за пределами методы дерева дерева. Для достижения этой цели просто сделать метод

avl_node* insert(avl_node *where, int value) 

частные (или защищены, по крайней мере) в классе и добавить общедоступный интерфейс:

void insert(int value) 
    { 
     root = insert(root, value); 
    } 

Затем в основной добавлении элементов просто позвонив по телефону

avlTree tree; 

    .... 
    tree.insert(item); 

EDIT ответить на вопрос, заданный в комментарии.

функции как display, inorder и т.д., должны быть обработаны таким же образом, как insert: объявить открытый, функции для запуска без параметров действия и защищенный метод с параметром рекурсивно выполнить его:

public: 
    void display()  { display(root, 0); } 
    void inorder()  { inorder(root); } 
    ..... 

protected: 
    void display(avl_node *node, int level) 
    { 
     if (node!=NULL) 
     { 
      display(node->right, level + 1); 
      if (node == root) 
       cout << "Root -> "; 
      else 
       cout << "  "; 
      cout << setw(5*level) << "" << node->data << endl; 
      display(node->left, level + 1); 
     } 
    } 

    void inorder(avl_node *node) 
    { 
     if (node) 
     { 
      inorder (node->left); 
      cout << node->data << " "; 
      inorder (node->right); 
     } 
    } 

затем используйте:

tree.display(); 
tree.inorder(); 
+0

Спасибо, теперь это имеет смысл.У меня есть еще один вопрос: что мне делать с инструкциями in/post/pre и дисплеем, чтобы остановить использование root в качестве параметра. – Bogdan

+0

@Bogdan См. Отредактированный ответ. – CiaPan

+0

спасибо, мне все равно удалось это сделать, но я взгляну на вашу интерпретацию – Bogdan

Смежные вопросы