How to build tree with the given input format? Total number of nodes is not given in the input.
How to build tree with the given input format?
1 2
1 has 2 children now move to its childrens
2 2
2 has two children (als 2 is children of 1)
3 0
3 is one of the children of 2 and it has zero children means leaf node
4 0
4 is 2nd children of 2 and it has zero children means leaf node
5 2
5 is 2nd children of 1 and it has two children 6 and 7 see next two lines
6 0
7 0
2 (this is the level no)
use recursion to take input
hint:
//Enter Node Data
int d; cin>>d;
Node* nn=new Node(d);
// Enter no of children for node#
int c; cin>>c;
nn->child_count=c;
nn->children=new Node*[c];
for (int i=0;i<c;i++){
nn->children[i]=InputForGenricTree();
}
return nn;
}
if you have more doubts regarding this feel free to ask
and if your doubt is resolved please mark it as resolved from your doubt section in your course
1 Like
thanks a lot, i now understood after dry running ur code
class Node{
public:
int data;
Node** children;// this is array which stores addresses of all children
int child_count;
Node (int d){
data=d;
children=NULL;
child_count=0;
}
};
1 Like