2014-06-30 115 views
-1

嘿,我试图写一个程序,将采取字符串列表(这些都是按顺序):二叉树搜索对我说谎吗?

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); 
    } 
} 
+3

算法不撒谎,如果他们给你结果你不喜欢,那么你教它错了。 – Jonast92

+0

@Isantipov我不知道你是否曾经在C中使用过调试器,但我可以确定他们在****中很痛苦。如果你没有什么建设性的话,为什么你甚至会关心评论? –

+0

你应该标记什么语言。我在猜C? – crashmstr

回答

2

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

解决方案:将malloc移到循环中。

+1

也应该给字符串一个真正的大小,否则它们会有缓冲区溢出(也是代码存在的问题)。 – crashmstr

+0

感谢Daniel Danrabos和'crashmstr'。您的两条评论现在为我提供了一个功能齐全的程序。再次感谢! – user3760978