in this we take int d in build tree () function.what if we make a templated node class .how can we define the datatype of d in buildtree() same as node class?
Binary tree build recursive issue
@Rj.25
Let’s say I am taking the data to be of type T , where T is a template class . My node class will look something like
template < class T >
class node {
public:
T data;
node*left;
node*right;
node(T d){
data = d;
left = NULL;
right = NULL;
}
};
Further there would be changes in the buildtree() as well. We would have to specify the data type everytime we call constructor of node class.
On the plus sign , d can be of any type now. String , float whatever you want.
string d;
cin>>d;
if(d==""){
return NULL;
}
node<string> * root = new node<string>(d);
root->left = buildTree();
root->right = buildTree();
return root;
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
in the answer given by you we got to know the dtatype of d before hand in buildtree function .ny question was that we do not know about the datatype of d while writing the code.we just know that it has the datatype same as the node class .then how can we write?
in the
int main() {
node n; // here u are required to tell the type of the node which is passed onto the other functions
buildTree();
}node* buildTree(){
T d;
cin >> d;
//
// computation logic
//
return nde;
}
so we are not required to mention string d in the buildTree() instead just write template type=> in this case T
it would accept tthe datatype of the node
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.