簡體   English   中英

在C二叉樹中插入函數?

[英]Insert function in C Binary Tree?

我在C語言中的二叉樹代碼根本沒有運行,我不確定為什么。 函數中有什么公然錯誤嗎? 它僅使用一次插入即可運行,但隨后又停止工作。 它只是一個簡單的函數,可以在樹的正確位置插入整數。

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


typedef struct trees Tree;
struct trees {
    int data;
    Tree *left;
    Tree *right;
};

Tree *inicio=NULL; 


void insert(int n){
        Tree *novo = (Tree*)malloc(sizeof(Tree));
        Tree *aux;
        Tree *pai;

        novo->data=n;
        novo->left=NULL;
        novo->right=NULL;
    if(inicio==NULL){
            inicio = novo;
            return;
    } else {
        aux = inicio;
        pai = NULL;
        while(1){
            pai = aux;
            if(n>pai->data){
                aux=aux->right;
                if(aux==NULL){
                    pai->right=novo;
                    return;
            } else {
                aux=aux->left;
                if(aux==NULL){
                    pai->left=novo;
                    return;
                }

            }
            }
        }
    }   
}

int main() {
    insert(9);
    insert(8);

    printf("[%p] -> (%p, %d, %p)\n",inicio,inicio->left,inicio->data,inicio->right);    

    return 0;
}

為了說明@kaylum點,這里是重新格式化的相關部分

while(1){
    pai = aux;
    if(n>pai->data){
        aux=aux->right;
        if(aux==NULL){
            pai->right=novo;
            return;
        } // end if(aux==NULL)
        else
        {  // else => aux != NULL
           aux=aux->left;
           if(aux==NULL){
               pai->left=novo;
               return;
           } // end if(aux==NULL)
        } // end else
    } // end if(n>pai->data)
} // end while

請注意, else return后無意義的噪音

while(1){
    pai = aux;
    if(n > pai->data){
        aux = aux->right;
        if(aux == NULL){
            pai->right = novo;
            return;
        }
        continue; // skip to next loop
    }
    // implying (n <= pai->data)
    aux = aux->left;
    if(aux == NULL){
        pai->left = novo;
        return;
    }
}

“更好”的實現可能會使用指向指針的指針並減少冗余代碼。

void insert(int n)
{
    Tree **pp = &inicio;

    while (*pp)
    {
        if ((*pp)->data < n)
            pp = &(*pp)->right;
        else
            pp = &(*pp)->left;
    }

    *pp = malloc(sizeof **pp);
    if (*pp)
    {
        (*pp)->data = n;
        (*pp)->left = (*pp)->right = NULL;
    }
}

暫無
暫無

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

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