2011-11-18 5 views
4

그래서 이진 트리를 생성하는 코드를 만들고 싶습니다. 예를 들어 1,6,2,10,8의 ints와 같은 데이터를 보유하고 있고 가장 큰 숫자를 얻은 후에 그 트리에서 삭제되면, 그리고 밀어 난 새로운 요소를 삽입 할 수 있습니다. 그리고 이것은 템플릿에 있어야하므로 트리에서 유지하고자하는 데이터 유형을 쉽게 변경할 수 있습니다. 지금 나는 템플릿을 사용하지 않고 템플릿을 사용하고 있습니다. 항목을 추가 할 수는 있지만 인쇄 할 수는 있지만 템플리트에 넣으려고하면 다음 오류가 발생합니다. 클래스 템플릿을 사용해야합니다. 템플릿 인수 목록. 무엇이 문제 일 수 있습니까? 어쩌면 나는 그것을 완전히 잘못하고있다. 어떤 제안이라도 환영합니다. 템플릿의 이진 트리

는 지금까지 다음과 같은 코드를 가지고 :

#include <iostream> 


using namespace std; 


template<class T> 
class BinaryTree 
{ 
struct Node 
    { 
     T data; 
     Node* lChildptr; 
     Node* rChildptr; 

     Node(T dataNew) 
     { 
      data = dataNew; 
      lChildptr = NULL; 
      rChildptr = NULL; 
     } 
    }; 
private: 
    Node* root; 

     void Insert(T newData, Node* &theRoot) 
     { 
      if(theRoot == NULL) 
      { 
       theRoot = new Node(newData); 
       return; 
      } 

      if(newData < theRoot->data) 
       Insert(newData, theRoot->lChildptr); 
      else 
       Insert(newData, theRoot->rChildptr);; 
     } 

     void PrintTree(Node* theRoot) 
     { 
      if(theRoot != NULL) 
      { 
       PrintTree(theRoot->lChildptr); 
       cout<< theRoot->data<<" ";; 
       PrintTree(theRoot->rChildptr); 
      } 
     } 

    public: 
     BinaryTree() 
     { 
      root = NULL; 
     } 

     void AddItem(T newData) 
     { 
      Insert(newData, root); 
     } 

     void PrintTree() 
     { 
      PrintTree(root); 
     } 
    }; 

    int main() 
    { 
     BinaryTree<int> *myBT = new BinaryTree(); 
     myBT->AddItem(1); 
     myBT->AddItem(7); 
     myBT->AddItem(1); 
     myBT->AddItem(10); 
     myBT->AddItem(4); 
     myBT->PrintTree(); 
    } 

답변

5

을 표현에서

new BinaryTree() 

식별자 BinaryTree 템플릿이 아닌 클래스입니다. 당신은 아마 의미했다

new BinaryTree<int>() 
+1

그것은 클래스 템플릿입니다 ... 그것은 클래스 템플릿입니다! – Marlon

+1

@Marlon, 클래스 템플릿? 혹시. 수업? 아마 아닐거야. 나는 Futurama를 보는 것을 멈출 필요가있다. ... – avakar

+0

확실하지 않다, 너희들이 이야기하고있는 것이지만, 실제로 지금 일하므로, 정말 고마워. –