c - 在C二叉树中插入函数?

标签 c 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

请注意,return之后的else是毫无意义的噪音

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;
    }
}

关于c - 在C二叉树中插入函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59080514/

相关文章:

c - 改进递归哈达玛变换

python - Python 中的 printf 格式 f 与 d

Angular 2 单击事件导致整个组件重新初始化(丢失状态)

c++ 在节点树中使用 'this'

c - 使用 BusyBox 的嵌入式 Linux 设备上的守护程序可以用 C 语言或脚本编写

c - -ansi -pedantic C 中的 64 位长度整数

c++ - 方法不占用 long long int 值显示错误

c - 通过 C 中的树向上传递值

python - 如何在 scikit-learn 中设置 ID3 算法?

c - scanf 未读取值