Reputation: 103
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;
}
Upvotes: 1
Views: 121
Reputation: 40145
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) );
Upvotes: 1