gpt4 book ai didi

c - Segmentation Fault 11 用C构建二叉树

转载 作者:太空宇宙 更新时间:2023-11-04 03:46:29 27 4
gpt4 key购买 nike

当我运行此代码以获取二叉树的长度时,出现段错误: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;
}

最佳答案

改变

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

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

关于c - Segmentation Fault 11 用C构建二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23944157/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com