I've spent many days trying to add strings recursively from a prefix expression like: + 1.5 * 13 2.5
inside a binary tree. I'm using the strtok
function to separate elements of the string, but then how can I add the elements to the tree?
My code is very similar to the GeeksForGeeks example: https://www.geeksforgeeks.org/building-expression-tree-from-prefix-expression/ , but here they only add characters as data on a node.
typedef struct node {
char * data;
struct node *left, *right;
} node;
// Function to recursively build the expression tree
char* add(node** p, char* a)
{
// If its the end of the expression
if (*a == '\0')
return '\0';
while (1) {
char* q = "null";
if (*p == NULL) {
// Create a node with *a as the data and
// both the children set to null
node* nn = (node*)malloc(sizeof(node));
nn->data = *a;
nn->left = NULL;
nn->right = NULL;
*p = nn;
}
else {
// If the character is an operand
if (*a >= '0' && *a <= '9') {
return a;
}
// Build the left sub-tree
q = add(&(*p)->left, a + 1);
// Build the right sub-tree
q = add(&(*p)->right, q + 1);
return q;
}
}
}
int main()
{
node* s = NULL;
char a[] = "3.5 + 4.7";
// (...) tokens
add(&s, str);
return 0;
}
Thank you very much for your help.
In the example of geeksforgeeks
they use char data
in the struct. But at your side, you use char * data
, so you should use strcpy
to copy data from strtok
to data
of struct. In this case, you have to allocate the memory for the data
of each node
. If you do not want to allocate, you can change the char * data
in struct node
to char data[20]
.
For example:
node* nn = malloc(sizeof(node));
if(!nn) {
//handle the error
}
nn->data = malloc((sizeof(char)*20) // For example max size of data is equal to 20
char * token = strtok(str, delim); // you choose delim as you want to split the string str
While(token!=NULL) {
strcpy(nn->data, token);
token = strtok(NULL, delim);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.