Im working with tree. Every node have object with Tree * values. I read data which looks like:
1
2
2
...
It means, put 1 as child of 0, put 2 as child of 1, put 3 as child o 2. In regular form: put x as child of i-1 where i is number of row.
I decided to make tree, looks like:
class Tree {
public:
int value;
stack <Tree*> children;
Tree ();
Tree (int x) {value = x;}
void wypisz();
};
So now when i read input i have something to do like this (but it doesn’t work):
int n,x;
scanf("%d",&n);
Tree **tab;
tab = (Tree **) malloc(sizeof(Tree*)*n);
Tree *n = 0;
tab[0] = new Tree(0);
for(int i=1;i<n;++i) {
scanf("%d",&x);
n = new Tree(x);
tab[i] = n;
tab[i-1]->children.push(n);
}
delete n;
So i need to n = new Tree(x); be a pointer to new object of tree, and add this pointer
to tab at [i] place and add this pointer to children of tab[i-1] element. What’s wrong with
this code?
Those lines doesn’t compile:
n = new Tree(x);
tab[i] = n;
With error:
- line: Value ot type “Tree *” cannot be assigned to an entity of type “int”.
- line: Value ot type “int” cannot be assigned to an entity of type “Tree *”.
First you declare
nas anint. Later you declarenas aTree*.These two declarations conflict, since they try to declare the same variable with two different types. To avoid the conflict, use two different variable names.