从现有树创建新树(左和右)
creating a new tree from the existing trees as left and right
我的代码与此线程中给出的代码类似。
template<class T>
class BinarySearchTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
T data;
tree_node( const T & thedata, tree_node * l = NULL, tree_node * r = NULL )
: data( thedata ), left( l ), right( r ) { }
};
tree_node* root;
public:
BinarySearchTree()
{
root = NULL;
}
}
在我的主程序中,需要这样做:
我有两棵树:
BinarySearchTree<T> tree1;
BinarySearchTree<T> tree2;
我需要创建一个新树:
根作为 T 的对象,左 = 树 1,右 = 树 2;
为此,我尝试添加此构造函数:
BinarySearchTree(const T& x, tree_node* l, tree_node* r);
并尝试从主调用:
BinarySearchTree<T> newTree(T object,tree1,tree2);
我知道这行不通,但我该怎么办?
编译错误:
错误 C2664: '二进制搜索树::二进制搜索树(常量 T &,二进制搜索树::tree_node *,二进制搜索树::tree_node *)' : 无法将参数 2 从"二进制搜索树 *"转换为"二进制搜索树::tree_node *"
首先:你对构造函数的调用不正确,应该是这样的:
BinarySearchTree<T> newTree(object,tree1,tree2);
我建议,实现一个所谓的复制构造函数,一个构造函数,将同一类的实例作为参数:
BinarySearchTree(const BinarySearchTree& other)
{
root = other.root; // propably you have to allocate it with "new"
}
这将允许您从子节点创建新树。
我希望我已经回答了你的问题,如果有什么不够清楚的地方,请随时问! :)
在实现您在这里尝试实现的目标后,您将遇到许多问题。首先,在连接树之后,您希望在根节点上存储的内容是最重要的,在许多情况下,生成的树不会是二叉搜索树。只需传递对指针的引用或指向树根节点指针的指针即可解决此编译器问题。
void Join(const T & thedata, tree_node *& l, tree_node &* r );
如果你用 * 定义你的函数参数,这说明编译器他们期望一个指向对象的指针。如果这样做,则必须给出对象的地址,而不是对象本身,例如:
BinarySearchTree<T> newTree(object,&tree1, &tree2);
您可以更改调用方法的方式,也可以更改方法定义以接受引用,就像使用 const T& 一样。
相关文章:
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 如何使用CLion在Mac上创建一个新的.txt文件
- 使用新运算符C++创建多维数组的简单方法
- C 矢量元素擦除与新向量创建
- 如何使用安置新操作员创建对象数组
- 我如何在参考上使用数据成员而不使用新关键字创建对象
- 在C++中为二叉搜索树创建一个删除函数
- 通过使用新操作员创建对象会导致未解决的外部符号错误C FTGL
- 使用新关键字创建的C 对象不会呈现;在堆栈上创建的对象确实可以
- 创建一个函数,该函数返回一个新的相同二叉树,并向所有预先存在的叶添加新节点
- 为二进制搜索树创建一个新节点
- 空二叉树创建 C/C++
- 部分模板绑定,将新模板创建为类型
- 二进制搜索树创建堆栈-overfow
- inotify-在目录树中的几个级别之后,无法将手表添加到新创建的目录中
- 管理用新char*创建但用自定义分配器分配给std::vector元素的内存块
- std::将自定义树转换为新树
- 在C++中为树创建新结构
- 使用受保护的方法而不是为继承树中的每个派生类创建新的虚拟函数,这是一种好的做法吗.例如,在描述中
- 从现有树创建新树(左和右)