【问题标题】:Binary-Tree in Template模板中的二叉树
【发布时间】:2011-11-19 02:00:15
【问题描述】:

所以我想编写一个代码,它创建一个二叉树,它保存数据,例如像 1,6,2,10,8 这样的整数,在弹出时我得到最大的数字,然后它被从树,并且在推送时我可以插入一个新元素。这应该在模板中,这样我就可以轻松更改要在树中保存的数据类型。现在我得到了树到目前为止,没有模板它工作得很好,我可以添加项目,我可以打印它们,但是当我尝试将它放入模板时,我收到以下错误:使用类模板需要模板参数列表。可能是什么问题呢?也许我做错了。欢迎提出任何建议。

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

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

【问题讨论】:

    标签: c++ templates binary-tree


    【解决方案1】:

    在表达式中

    new BinaryTree()
    

    标识符BinaryTree 是一个模板,而不是一个类。你可能是说

    new BinaryTree<int>()
    

    【讨论】:

    • 这是一个类和一个模板......这是一个类模板!
    • @Marlon,类模板?也许。班级?也许不是。我需要停止看未来世界......
    • 不确定,你们在说什么,但现在确实有效,非常感谢。
    • @Toma,别担心,我们只是在开玩笑:)
    • 嗯,我希望我能多打扰你一点,也许你可以帮我解决这个问题,我只是通过项目请求阅读,类似的,我必须在上面做这个在所描述的问题中,但它就像二叉树应该代表一个优先级队列。这就是为什么在请求中我必须使用 push 和 pop 来获取我的数据或删除它。那么我怎么能将我的树用作优先队列,或者他已经是一个(我认为不是,但谁知道)?我希望我能解释一下。 (我应该将此作为新问题吗?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 2018-09-20
    相关资源
    最近更新 更多