当我运行此代码以获取二叉树的长度时,我得到一个分段错误:11错误 我已经尝试纠正它,我可以让它运行的唯一方法是通过调用大小函数只为左或右节点。当我以这种方式运行它(根据我的说法是正确的)我得到了错误。
#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;
}
答案 0 :(得分:1)
更改
node* node = malloc( sizeof(node) );//<<-sizeof(node) : It has been interpreted as a variable name, not the type.
到
node* node = malloc( sizeof(struct node) );