Binary-Tree in Template

∥☆過路亽.° 提交于 2019-12-04 14:31:44

问题


so i want to make a code, that creates a binary tree, that holds data, for example ints like 1,6,2,10,8 and on pop i get the biggest number, and after that it gets deleted from the tree, and on push i can insert a new element. And this should be in a template so i can easy change the data type i want to hold in the tree. Now i got the tree so far, without template it is working fine thought, i can add items, and i can print them, but when i try to put it in a template, i get the following error: use of class template requires template argument list . What could be the problem? Maybe i am doing it totally wrong. Any suggestions are welcome.

I got the following code so far:

#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();
    }

回答1:


In the expression

new BinaryTree()

the identifier BinaryTree is a template, not a class. You probably meant

new BinaryTree<int>()


来源:https://stackoverflow.com/questions/8186818/binary-tree-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!