【发布时间】:2020-04-29 22:38:11
【问题描述】:
我花了很多天时间尝试从一个前缀表达式递归地添加字符串,例如:二叉树中的+ 1.5 * 13 2.5。我正在使用strtok 函数来分隔字符串的元素,但是如何将元素添加到树中?
我的代码与 GeeksForGeeks 示例非常相似:https://www.geeksforgeeks.org/building-expression-tree-from-prefix-expression/,但这里它们只在节点上添加字符作为数据。
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;
}
非常感谢您的帮助。
【问题讨论】:
-
一旦你有来自
strtok的字符串令牌,调用strdup进行复制并将其分配给nn->data。不要忘记在某个时候释放strdup内存。 -
@kaylum,据我所知,
strdup不是标准功能,我错了吗? -
@Hitokiri 你没看错。这是一个 posix 函数,但不是 C 标准的一部分。
标签: c tree binary expression prefix