2012-06-04 54 views
2

我想實現一個AVL樹,似乎與我如何使用我的節點類有問題。我得到錯誤C4430:與第二個getHeight缺少類型說明符我想我指定類型爲子樹的節點?使用C++實現AVL添加?

template <typename T> 
class SetAVL 
{ 
public: 
int getHeight() 
{ 
    return getHeight(root); 
} 
// Complaining about this line 
int getHeight(const Node<T> *subtree) 
{ 
    // If we are at a leaf 
    if (subtree == NULL) 
     return 0; 

    return 1 + max(getHeight(subtree->left), getHeight(subtree->right)); 
} 

void add(Node<T> *item) 
{ 
    Node<T> *t = new Node<T>(item); 
    insert(root, t); 
} 

void insert(Node<T> *root, Node<T> *t) 
{ 
    if (root == NULL) 
     root = t; 
    else 
    { 
     if (t->item < root->item) 
      insert(root->left, t); 
     else if (t->item != root->item) 
      insert(root->right, t); 
     else 
      delete t; 
    } 
} 

protected: 
    template <typename T> 
    class Node 
    { 
    public: 
     T item; 
     Node *left; 
     Node *right; 
     int height; 

     Node(T item) 
     { 
      this->item = item; 
      this->left = NULL; 
      this->right = NULL; 
      this->height = 0; 
     } 
    } 

    Node<T> *root; 
    int treeSize; 
} 

回答

2

似乎需要指定正確的類型爲左,右點

Node *left; 
Node *right; 

應該

Node<T> *left; 
Node<T> *right; 

我使用它之前,移動節點的定義。順便說一句,你失去了';'在類節點定義的末尾。

template <typename T> 
class SetAVL 
{ 
protected: 
    template <typename T> 
    class Node 
    { 
    public: 
     T item; 
     Node<T> *left; 
     Node<T> *right; 
     int height; 

     Node(T item) 
     { 
      this->item = item; 
      this->left = NULL; 
      this->right = NULL; 
      this->height = 0; 
     } 
    }; 

    Node<T> *root; 
    int treeSize; 
public: 
    int getHeight() 
    { 
     return getHeight(root); 
    } 

    int getHeight(const Node<T> *subtree) 
    { 
     // If we are at a leaf 
     if (subtree == NULL) 
      return 0; 

     return 1 + max(getHeight(subtree->left), getHeight(subtree->right)); 
    } 

    void add(Node<T> *item) 
    { 
     Node<T> *t = new Node<T>(item); 
     insert(root, t); 
    } 

    void insert(Node<T> *root, Node<T> *t) 
    { 
     if (root == NULL) 
      root = t; 
     else 
     { 
      if (t->item < root->item) 
       insert(root->left, t); 
      else if (t->item != root->item) 
       insert(root->right, t); 
      else 
       delete t; 
     } 
    } 


}; 

希望它有幫助!

+0

謝謝我沒有注意到,我忘了添加這些。儘管如此,我仍然在同一行上遇到同樣的問題。 – LF4

+0

很酷的感謝工作,我養成了公開,保護,私人的習慣。還從前一個結構體中複製Node類我非常感謝您指出缺少的';'。 – LF4

+0

@ LF4如果是,則可以添加類節點預先聲明「template class Node;」在使用之前。 – JsDoITao