When building a tree structure with C,
// node
structure tnode
{
structure tnode*left;
char*value;
structure tnode*right;
};
structure tnode*talloc(void)
{
return(struct tnode*) malloc(sizeof(struct tnode));
}
structure tnode*gentree (struct tnode*p, char*w)
{
if(p==NULL)
{
// Generate when you come to the end
p=talloc();
strcpy(p->value,w);
p->left=p->right=NULL;
}
else
{
// Scan to NULL from side to side if it's not the edge
p->left=gentree(p->left,w);
p->right=gentree(p->right,w);
}
return p;
}
void main()
{
structure tnode*root;
root = NULL;
root=gentree(root, "aaa");
printf("%s\n", root->value);
putchar('\n');
root=gentree(root, "bbb");
printf("%s\n", root->value);
printf("%s\n", root->left->value);
printf("%s\n", root->right->value);
}
This is how I try to create it.
As for the structure of the tree, I would like aaa to branch into two bbb, but the result is
aaa
I want it to be bbb//aaa
bbb
bbb
And somewhere aaa will be rewritten to bbb. When I checked the rewritten address as below, the two addresses were the same.
root=gentree(root, "aaa");
printf("%d\n", root);
root=gentree(root, "bbb");
printf("%d\n", root);
This may be rudimentary, but please reply.
c
Uh, does it really work?
// node
structure tnode
{
structure tnode*left;
char*value;
structure tnode*right;
};
The value is not assigned by the pointer.
The quick one (ignoring efficiency, etc.) is
strcpy(p->value,w);
Before
p->value=malloc(strlen(w)+1)*sizeof(char));
I see.
If you're thinking about efficiency by allocating memory multiple times, it's a trick behind the scenes.
// node
structure tnode
{
structure tnode*left;
structure tnode*right;
char value [0];
};
structure tnode*talloc(size_tval_size)
{
return(struct tnode*) malloc(sizeof(struct tnode) + sizeof(char)*val_size);
}
There is also a way.
© 2024 OneMinuteCode. All rights reserved.