模板中的二叉树
Binary-Tree in Template
本文关键字:二叉树 更新时间:2023-10-16
所以我想写一个代码,创建一个二叉树,用来保存数据,比如像1,6,2,10,8这样的整数,pop时我得到最大的数字,之后它从树中被删除,push时我可以插入一个新元素。这应该是在一个模板,所以我可以很容易地改变数据类型,我想保持在树。现在我得到了树到目前为止,没有模板它是工作良好的思想,我可以添加项目,我可以打印它们,但是当我试图把它放在一个模板,我得到以下错误:使用类模板需要模板参数列表。有什么问题吗?也许我完全做错了。欢迎提出任何建议。
到目前为止,我得到了以下代码:#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>()
相关文章:
- 从父数组测试用例构造二叉树失败
- 打印时有二叉树问题.用户输入不打印任何内容
- 试图找到二叉树的深度
- 二叉树结构平衡,使用递归时EXC_BAD_ACCESS
- 指向二叉树中新节点的指针
- 我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- C++:如何计算二叉树中其值模块高度小于 2 的节点数?
- 二叉树级别顺序遍历在leetcode中
- 运行无限循环的最小二叉树问题
- 打印二叉树中的常见元素
- 二叉树基准测试结果
- 带有矢量重复值的二叉树打印出来
- 签入二叉树的函数是平衡C++
- 我有两棵二叉树.我想在不更改输入树的情况下深度复制两个二叉树的结果
- 如何计算给定数字在二叉树中出现的次数?
- 为什么我的二叉树会覆盖其根的叶子?
- 将二叉树的节点插入链表 (C++)
- 二叉树级别顺序插入 c++
- 在 C++ 中创建两个不同的二叉树时出现分段错误
- 如何在使用 ItemType 的模板类时将新节点插入二叉树 c++.(我是 c++ 的新手)