二进制搜索树插入

时间:2013-11-21 23:30:34

标签: c

我只想在二叉搜索树中addAlbum,但树将根据发布年份构建。我编写了代码,但它没有运行...

#include<stdio.h>
#include<stdlib.h>

typedef struct treeNode {
    int releaseYear;
    char singerName[50];
    char albumTitle[50];
    struct treeNode *left;
    struct treeNode *right;
} treeNode;

treeNode *addAlbum(treeNode *node,int releaseYear,char singerName[50],char albumTitle[50]) {
    if(node==NULL) {
        treeNode *temp;
        temp=(treeNode *)malloc(sizeof(treeNode));
        temp -> releaseYear=releaseYear;
        temp -> singerName[50]=singerName[50];
        temp -> albumTitle[50]=albumTitle[50];
        temp ->left = NULL;
        temp ->right = NULL;
        return temp;
    }

    if(releaseYear > (node -> releaseYear)) {
        node ->right=addAlbum(node->right,releaseYear ,singerName,albumTitle);
    }
    else if(releaseYear<(node -> releaseYear)) {
        node ->left=addAlbum(node->left,releaseYear, singerName,albumTitle);
    }
    else {
        return node;
    }

}

int main() {
    treeNode *root;
    int releaseYear;
    char singerName[50];
    char albumTitle[50];
    root=addAlbum(root,1995,"a","d");
    root=addAlbum(root,1998,"b","c");
    printf("singers = s\n",singerName[50]);
    printf("albumTitles = %c\n",albumTitle[50]);
    printf("years = %d\n",releaseYear);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

有很多问题:

1)您必须将root初始化为NULL,否则它可能包含任何垃圾值,并且第一次调用时树的构造可能会失败。

treeNode *root = NULL;

2)您只分配char singerNamealbumTitle strcpy,两者都是出界(有效数组索引为0 ... 49)。要复制实际字符串,请使用strcpy(temp->singerName, singerName); // was: temp->singerName[50]=signerName[50]; strcpy(temp->albumTitle, albumTitle);

releaseYear

3)如果else对于两个节点是相同的,则您的代码将丢失新节点,因为它甚至没有创建。移除addAlbum中的最终else并从第一个(仅限现在)node中移除条件,如果您未在此期间创建新条件,则始终返回if (releaseYear > node->releaseYear) { node->right = addAlbum(node->right, releaseYear, singerName, albumTitle); } else { node->left = addAlbum(node->left, releaseYear, singerName, albumTitle); } return node; 拨打:

printf

4)main中的root次呼叫只打印出未初始化的局部变量的垃圾值。从main中删除除{{1}}之外的所有其他本地变量。实现树的遍历以打印出存储在其中的值。