【问题标题】:Add String nodes to an Expression Tree将字符串节点添加到表达式树
【发布时间】: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-&gt;data。不要忘记在某个时候释放strdup 内存。
  • @kaylum,据我所知,strdup 不是标准功能,我错了吗?
  • @Hitokiri 你没看错。这是一个 posix 函数,但不是 C 标准的一部分。

标签: c tree binary expression prefix


【解决方案1】:

在geeksforgeeks 的示例中,他们在结构中使用char data。但是在你身边,你使用char * data,所以你应该使用strcpy将数据从结构的strtok复制到data。在这种情况下,您必须为每个node 的data 分配内存。如果不想分配,可以将struct node中的char * data改成char data[20]。

例如:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多