gpt4 book ai didi

c++ - 从现有树中创建一棵新树作为左和右

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:58:37 25 4
gpt4 key购买 nike

我的代码类似于 this thread 中给出的代码.

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;

我需要创建一棵新树:

root 作为 T 的对象,left = tree1 right = tree2;

为此,我尝试添加此构造函数:

BinarySearchTree(const T& x, tree_node* l, tree_node* r); 

并尝试从 main 调用:

BinarySearchTree<T> newTree(T object,tree1,tree2);

我知道这行不通,但我该怎么办?

编译错误:

错误 C2664:“BinarySearchTree::BinarySearchTree(const T &,BinarySearchTree::tree_node *,BinarySearchTree::tree_node *)”:无法将参数 2 从“BinarySearchTree *”转换为“BinarySearchTree::tree_node *”

最佳答案

首先:你对构造函数的调用不正确,应该是这样的:

BinarySearchTree<T> newTree(object,tree1,tree2);

我建议,实现一个所谓的复制构造函数,一个构造函数,将同一类的实例作为参数:

BinarySearchTree(const BinarySearchTree& other)
{
root = other.root; // propably you have to allocate it with "new"
}

这会让您从子节点创建一棵新树。

我希望我已经回答了你的问题,如果有任何不够清楚的地方,请随时提出! :)

关于c++ - 从现有树中创建一棵新树作为左和右,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5968371/

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