0

我试图创建一个莫尔斯编码器 - 解码器,我必须用二叉搜索树(而不是数组)来做。下面的部分应该采用一个字符数组(我们之前从一个文本文件创建),并基于它创建一个搜索树。

在 btree_base 字符数组中,我们有数据,格式为: “(字母)(摩尔斯电码)|(字母)(摩尔斯电码)|” 等等(例如,e .|t -|z --..| ...)。

注意:字符串包含数据的方式是通过从头到尾读取它,将创建一个平衡的搜索树

二叉树的创建是不成功的,我知道,因为当我运行代码时,btree_print 函数没有在控制台上打印任何内容,我发现这是因为传递了一个 NULL 指针。

我的问题是为什么会这样以及如何解决这个问题?是我弄乱了指针,还是在传递根指针时需要使用双重间接?我不太了解 ** 指针,所以我尽量避免使用它们。

typedef struct BinTree{
    char letter;
    char code[6];
    struct BinTree *left, *right;
} BTree;

BTree* add(BTree* root, char ch, char* code, int length){
    int i;
    char a;
    if (root == NULL) {
        BTree *new = (BTree*) malloc(sizeof(BTree));
        new->left = new->right = NULL;
        new->letter = ch;
        for(i=0; i<length; i++) new->code[i] = code[i];
        new->code[length] = '\0';
        return new;
    }

    a=root->letter;

    if (ch < a) root->left = add(root->left, ch, code, length);
    else if (ch > a) root->right = add(root->right, ch, code, length);

    return root;
}

void build(BTree* root, char* c, int length){
    int i, size=-1;
    char b, k[6];
    for(i=0; i<length; i++){
        if(size==-1) b=c[i];
        if(c[i]==' ') size=0;
        if(size!=-1 && c[i]!='|'){
            k[size]=c[i];
            size++;
        }
        if(c[i]=='|'){
            k[size]='\0';
            root=add(root, b, k, size);
            size=-1;
        }
    }
}

void btree_print(BTree* root){
    if(root == NULL) return;

    printf("%c %s\n",root->letter,root->code);
    btree_print(root->left);
    btree_print(root->right);
}

void btree_del(BTree* root){
    if(root==NULL) return;

    btree_del(root->left);
    btree_del(root->right);
    free(gyoker);
}

int main(){
    char btree_base[238];
    BTree* bin_root = NULL;

    build(bin_root, btree_base, 238);

    btree_print(bin_root);

    btree_del(bin_root);
    return 0;
}
4

1 回答 1

1

因为您通过值传递根节点build,所以对其值所做的任何更改都不会反映到调用函数。因此,正如您猜想的那样,您需要传入一个指向根的指针,这将使其成为BTree **.

build(&bin_root, btree_base, 238);

然后在内部build,当您想要访问根节点时,您必须root首先通过在其前面加上*这样的前缀来取消引用:

*root=add(*root, b, k, size);

add也可以从这样的工作中受益,而不是返回更新的节点。既然build已经有了一种BTree **方法,您就root可以像这样通过

add(root, b, k, size);
于 2017-12-01T13:44:37.463 回答