C中的二叉搜索树,分段故障错误

时间:2016-04-23 18:24:00

标签: c pointers segmentation-fault binary-search-tree

我在使用C编写BST时遇到问题。我一直遇到分段错误错误。我认为问题源于insertNode函数。我在函数中添加了printf()语句,并在函数调用之后直接查看是否添加了newNode。请忽略其余的代码,因为它没有完成,只是试图让insertNode函数起作用。

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

//structure for node
struct btNode {
    int data;
    struct btNode *left;
    struct btNode *right;
};

//prototypes
struct btNode* createNode(int x);
void insertNode(struct btNode *tree, struct btNode *root);

int main(){
    int x,n=-1,i=0; //local variables

    struct btNode *head=NULL;

    while (n <= 0){
        printf("Enter the number of nodes in the Tree(>0): ");
        scanf("%i", &n);
    }


    while(i < n){
        printf("Enter an integer: ");
        scanf("%i", &x);
        struct btNode *newNode=createNode(x);
        insertNode(head,newNode);
        printf("%d",head->data); //breaks program here????

        i++;
    }

    while (x < 0){
        printf("Enter a integer from 0-5: ");
        scanf("%i",&x);

        if (x == 0){
            printf("Program Exit.\n");

            exit(0);

        }else if(x==1){


        }else if(x==2){


        }else if(x==3){

        }else if (x==4){

        }else if(x==5){

        }

        x=-1;
    }

    return 0;
}

//creates and returns a pointer to a new node
struct btNode* createNode(int x)
{
    struct btNode *newNode;
    newNode=(struct btNode*)malloc(sizeof(struct btNode));

    if (newNode == NULL){
        printf("Memory Allocation Failed./n");
        exit(20);
    }else{
        newNode->data=x;
        newNode->left=NULL;
        newNode->right=NULL;
        return newNode;
    }
}


void insertNode(struct btNode *tree, struct btNode *newNode){
    if (tree==NULL){
        tree=newNode;
        printf("%d",tree->data); //works fine here!
    }else if(tree->data <= newNode->data){
        insertNode(tree->right, newNode);
    }else if(tree->data > newNode->data){
        insertNode(tree->left, newNode);
    }
}

1 个答案:

答案 0 :(得分:1)

node插入树结构后,必须返回struct btNode *insertNode(struct btNode *tree, struct btNode *newNode){ if (tree==NULL){ tree=newNode; printf("%d", tree->data); //works fine here! return tree; }else if(tree->data <= newNode->data){ tree->right = insertNode(tree->right, newNode); return tree; }else if(tree->data > newNode->data){ tree->left = insertNode(tree->left, newNode); return tree; } } 。所以你的正确功能是:

head = insertNode(head, newNode);

同时修改你的电话:

show