2014-06-30 38 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