Reputation: 1590
My code is similar to the one given in 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;
}
}
In my main program, there a need for this:
I have two trees:
BinarySearchTree<T> tree1;
BinarySearchTree<T> tree2;
I need to create a new tree with:
root as an object of T and left = tree1 and right = tree2;
To do this I tried to add this constructor:
BinarySearchTree(const T& x, tree_node* l, tree_node* r);
and trying to call from main:
BinarySearchTree<T> newTree(T object,tree1,tree2);
I understand this won't work but what should I do?
Compile Error:
error C2664: 'BinarySearchTree::BinarySearchTree(const T &,BinarySearchTree::tree_node *,BinarySearchTree::tree_node *)' : cannot convert parameter 2 from 'BinarySearchTree *' to 'BinarySearchTree::tree_node *'
Upvotes: 2
Views: 268
Reputation: 11
There are many problems which you will surface after implementing what you are trying to achieve here. First of all after joining the trees the way you want what are you storing at the root node is most important and in many cases the resultant tree will not be a binary search tree. you can solve this compiler issue just by passing reference to pointer or pointer to pointer of root node of the trees.
void Join(const T & thedata, tree_node *& l, tree_node &* r );
Upvotes: 1
Reputation: 5651
If you define your function arguments with a * this says the compiler they expect a pointer to an object. If you do this you must give the address of the object, not the object itself like:
BinarySearchTree<T> newTree(object,&tree1, &tree2);
You can either change how you call the method or you can change the methods definition to accept a reference as you do with const T&.
Upvotes: 0
Reputation: 35059
First of all: your call of the constructor is not correct, it should be like this:
BinarySearchTree<T> newTree(object,tree1,tree2);
I would suggest, to implement a so called copy constructor, a constructor, taking an instance of the same class as argument:
BinarySearchTree(const BinarySearchTree& other)
{
root = other.root; // propably you have to allocate it with "new"
}
this would let you create a new tree from a child node.
I hope I have answered your question, feel free to ask if anything is not clear enough! :)
Upvotes: 1