簡體   English   中英

Segmentation Fault 11在C中構建二叉樹

[英]Segmentation Fault 11 Building Binary Trees in C

當我運行此代碼以獲取二叉樹的長度時,出現分段錯誤: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) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM