Sunday, 11 August 2013

Create a string with node of BST that has the same value

Create a string with node of BST that has the same value

I've a struct like (BST):
typedef struct node {
char* name;
int age;
struct node* left;
struct node* right;
} node_t;
and i've to make a function like: char* getSameAge(node_t* s, int age)
that returns a string like name1:name2:....nameN with node that has == age
I made this solution, it works with tests but using valgrind it gives me
errors...does anyone give me an advice or an alternative/better solution?!
void visitTree(node_t* s,char buf[N],int age) {
if(s!=NULL) {
visitTree(s->left,buf,age);
if(s->age == age) {
if(strlen(buf) == 0) strcpy(buf,s->name);
else{
strcat(buf,s->name);
if(s->left != NULL || s->right != NULL) strcat(buf,":");
}
}
visitTree(s->right,buf,age);
}
}
char* getSameAge(node_t* s, int age) {
char buf[N];
visitTree(r,buf,age);
if(strlen(buf) == 0) {
return NULL;
}
else {
char *aux = malloc(strlen(buf));
strcpy(aux,buf);
return aux;
}
}

No comments:

Post a Comment