在C中为字符串实现二进制搜索树

时间:2014-02-06 22:21:50

标签: c string binary-search-tree

我正在尝试在C中为字符串实现BST。 我是C的新手,来自java背景所以请原谅我的错误。 我的节点声明如下所示。

struct node {
    char *word;
    struct node *left;
    struct node *right;
};

static struct node *root = NULL;

然后我尝试简单地将一个节点添加到树的开头 到目前为止,这是我的代码。

int ws_add_word(char *word)
{
int n;
struct node *tmp = root;

// check if word is alrady there
n = strcmp(word, (*tmp)->word);
if (word_tree == NULL){
    (*root)->word = word;
    return 1;
} else if (n == 0){ //word present
    return 1;
} else if(n > 0){ //word bigger add to right
    if ((*root)->right == NULL){
        (*root)->right = word;
        return 1;
    }
} else if(n < 0){ //word smaller add to left
    if ((*root)->left == NULL){
        (*root)->left = word;
        return 1;
    }
}

// if tree full return false, else true
if (word_count >= tree_size){
    return 0;
} else{
    return 1;
}
}

如果代码设法插入单词,则代码只需返回1,如果不插入单词,则返回0。

我收到错误:' - &gt;'的无效类型参数(有'struct node')n = strcmp(word,(* tmp) - &gt; word); 看起来它不接受' - &gt;'我不知道如何引用节点中的数据。 当我使用int而不是char进行数字时,它工作得很好。 非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

a->b已取消引用a,您需要的是tmp->word

答案 1 :(得分:0)

不看你的逻辑:

如果您有(struct node *)类型的对象,那么要访问它的成员,您应该执行以下操作之一:

Option 1: (*foo).member
Option 2: foo->member

不是两个。

答案 2 :(得分:0)

小提示: 如果你声明结构使用typedef它会让你的代码变得更漂亮:

typedef struct node_t {
char *word;
struct node *left;
struct node *right;
}; *node; 
node root = NULL;
相关问题