当我运行此代码以获得二叉树的长度时,我得到分割错误:11错误。
我试过修正它,唯一能让它运行的方法是只调用左右节点的size函数。当我以这种方式运行它时(根据我是正确的),我得到了错误。
#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.
node* node = malloc( sizeof(struct node) );