模板中的二进制树

时间:2011-11-18 17:57:43

标签: c++ templates binary-tree

所以我想创建一个代码,它创建一个包含数据的二叉树,例如像1,6,2,10,8这样的内容,在pop上我获得最大的数字,之后它会被删除树,在推我可以插入一个新元素。这应该在一个模板中,这样我就可以轻松更改我想要在树中保存的数据类型。现在我得到了这棵树到目前为止,没有模板它工作正常,我可以添加项目,我可以打印它们,但是当我尝试将它放在模板中时,我得到以下错误:使用类模板需要模板参数列表。可能是什么问题呢?也许我做错了。欢迎任何建议。

到目前为止,我得到了以下代码:

#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 个答案:

答案 0 :(得分:5)

在表达式

new BinaryTree()

标识符BinaryTree是模板,而不是类。你可能意味着

new BinaryTree<int>()