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