简体   繁体   中英

Segmentation Fault 11 Building Binary Trees in C

When I run this Code to get the Length of a Binary tree I get a Segmentation Fault: 11 Error.
I've tried correcting it and the only way I can get it to run is by calling the size function just for the left or right nodes. When I run it this way (which according to me is correct) I get the error.

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

struct node {
    int data;
    struct node* left;
struct node* right;
};

typedef struct node node;

node* newNode( int data ){
    node* node = malloc( sizeof(node) );
    assert(node);
    node->data = data;
    node->left = NULL;
    node->right = NULL;

    return node;
}

node* insert( node* node, int data ) {
    if( node == NULL){
        return newNode(data);
    }
    else{
        if( data <= node->data ){
            node->left = insert(node->left, data);
        }
        else{
            node->right = insert(node->right,data);
        }
    }
    return node;
}

node* buildOneTwoThree() {
    node* root = newNode(2);
    root->left = newNode(1);
    root->right = newNode(5);
    return root;
}

int size( node* tree ) {
    int n = 0;
    if( tree == NULL ){
        return 0;
    } else {
        return size(tree->left) + 1 + size(tree->right);
    }
}


int main(){

    node* tree = NULL;
    tree = buildOneTwoThree();
    printf("size = %i \n", size(tree)+size(tree->right) );

    return 0;
}

change

node* node = malloc( sizeof(node) );//<<-sizeof(node) : It has been interpreted as a variable name, not the type.

to

node* node = malloc( sizeof(struct node) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM