簡體   English   中英

C二進制搜索樹插入

[英]C Binary Search Tree insertion

typedef struct word {
    char *str;             
    int freq;             
    struct word *right;
    struct word *left;
    } Word;



Word *root = NULL;  //global

while(pCounter != NULL){
            if(root == NULL){
                Word *x = (Word *)malloc(sizeof(Word));
                x->str = (char*)malloc(strlen(pCounter->str)+1);
                //printf("%s", node->str);
                strcpy(x->str,pCounter->str);
                x->freq = pCounter->freq;
                x->left = NULL;
                x->right = NULL;
                root = x;
                }
                else {
                    Insert(pCounter, root);
                }
            pCounter = pCounter ->pNext;
        }


void * Insert(Word *node, Word *root)
        {
            printf("inserted%s\n", node->str);
            if(root==NULL)
            {
                Word *x = (Word *)malloc(sizeof(Word));
                x->str = (char*)malloc(strlen(node->str)+1);
                //printf("%s", node->str);
                strcpy(x->str,node->str);
                x->freq = node->freq;
                x->left = NULL;
                x->right = NULL;
                return x;
                //node = root;
            }
            else if (strcmp(node->str, root->str)==0){

                root -> freq = root->freq+1;
            }
            else if (strcmp(node->str, root->str)<1){

                root->left = Insert(node,root->left);
            }
            else {
                root->right = Insert(node, root->right);    
            }

            return node;


        }

void ordered(Word *n){
            //printf("ordered");
    if(n != NULL){
        ordered(n->left);
        printf("%-30s   %5d\n", n->str, n->freq);
        ordered(n->right);
            }   
        }

我正在嘗試構建一個二進制搜索樹,以將鏈接列表處理為有序的bst。 我可以得到root的輸出以正確顯示,但沒有其他顯示。 它吐出一些垃圾,我不確定為什么。 我設置了一個printf語句,它表明它正在插入實際的字符串。 難道我做錯了什么? 這不是全部代碼,但我認為足夠了,這樣人們就可以了解我在做什么。 有什么建議嗎?

return node ; -> return root; 根據BLUEPIXY的評論,這是正確的答案。– BLUEPIXY 2分鍾前

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM