gpt4 book ai didi

c++ - 模板中的二叉树

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:48:04 24 4
gpt4 key购买 nike

所以我想编写一个代码,创建一个二叉树,保存数据,例如像 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();
}

最佳答案

在表达式中

new BinaryTree()

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

new BinaryTree<int>()

关于c++ - 模板中的二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8186818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com