二叉树搜索对我说谎吗?

时间:2014-06-30 15:35:46

标签: c binary-search-tree inorder

嘿我试图编写一个程序来获取字符串列表(这些是按顺序排列的):

polymorphism
object
templates
structure
class
pointer
reference
traversal
inheritance
exceptions
recursive
overloading

然后将这些字符串存储在二叉树中,最后进行有序遍历。 但是,我遇到了一个我无法解决的问题。我添加节点的功能一直告诉我,我已经添加了节点,但它实际上从未添加过?我的输出是这样的:

ADDED NODE: polymorphism
ERROR: Same Data: object, object
ERROR: Same Data: templates, templates
ERROR: Same Data: structure, structure
ERROR: Same Data: class, class
ERROR: Same Data: pointer, pointer
(etc...)
ERROR: overloading, overloading
ERROR: overloading, overloading
FINISHED BUILDING

overloading

最后,这里是源代码:

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

struct tree {
    char* data;
    struct tree *left;
    struct tree *right;
};

void buildTree(struct tree**);
void printAlpha(struct tree*);
void insert(struct tree **root, char *n);

int main(int argc, char* argv[]) {
    struct tree* myTree = NULL;

    buildTree(&myTree);
    printf("FINISHED BUILDING\n\n");
    printAlpha(myTree);

    system("PAUSE");
    return 0;
}

/*Builds tree from text file*/
void buildTree(struct tree **root) {
    FILE* fIn = fopen("./in.txt", "r");
    char* input = (char*) malloc(sizeof(char));

    if(!fIn) {
        printf("ERROR: Cannot find file\n");
        return;
    }

    while(!feof(fIn) && fscanf(fIn, "%s", input)) {
        // printf("INP:%s\n", input);
        insert(root, input);
    }
}

void insert(struct tree **root, char *n) {
    if (*root == NULL) {
        // found the spot, create and insert the node
        struct tree *newNode = NULL;
        newNode = (struct tree*) malloc(sizeof(struct tree) );
        newNode->data = n;
        newNode->left = NULL;
        newNode->right = NULL;
        *root = newNode;

        printf("ADDED NODE: %s\n", newNode->data);
    }

    else if(strcmp(n, (*root)->data) < 0)
    insert(&((*root)->left), n);
    else if(strcmp(n, (*root)->data) > 0)
    insert(&((*root)->right), n);
    else
    printf("ERROR: Same data: %s, %s\n", (*root)->data, n);
}

/*In order traversal*/
void printAlpha(struct tree *root) {
    struct tree *curNode = root;

    /*If empty something went wrong*/
    if(!curNode) {
        printf("Error: Binary Tree Is Empty!\n");
        //  return;
    }

    if(curNode->left != NULL) {
        printAlpha(root->left);
    }

    printf("%s\n", curNode->data);

    if(curNode->right != NULL) {
        printAlpha(curNode->right);
    }
}

1 个答案:

答案 0 :(得分:2)

您正在创建单个字符串(char* input = (char*) malloc(sizeof(char));)并且每次都会覆盖其内容。您将此单个字符串插入树中,然后下次将其与自身进行比较。

解决方案:在循环内移动malloc