我的“sumAtBis”代码有什么问题?

问题描述 投票:0回答:1

我在这里询问有关计算树中给定深度的总和的函数的问题,它在除最后一级之外的所有情况下都有效,编译器给了我这个:

[Done] exited with code=3221225477 in 0.309 seconds
这是我的代码和你需要的一切(还有更多其他功能和东西,但我认为这已经足够了):

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef int element;
typedef struct node{
    element e;
    struct node * left;
    struct node * right;
}node;
typedef node * tree;
int isEmpty(tree a){
    return a==NULL;
}
element root(tree a){
    return a->e;
}
tree left(tree a){
    return a->left;
}
tree right(tree a){
    return a->right;
}
int max(int x,int y){
    return x>y?x:y;
}
int sumAtBis(tree a, int n, int i){
    if(i==n){
        if(isEmpty(a))
            return 0;
        else
            return root(a);
    }
    return sumAtBis(left(a),n,i+1)+sumAtBis(right(a),n,i+1);
    
}
int sumAt(tree a, int n){
    return sumAtBis(a,n,0);
}
int testSumAtBis(tree a, int n, int i){
    return sumAt(a,n)==0?1:0;
}
int testSumAt(tree a, int n){
    return testSumAtBis(a,n,0)==0?1:0;
}
int main(){
    node g={-1,NULL,NULL};
    node f={1,NULL,NULL};
    node e={0,&f,&g};
    node d={0,NULL,NULL};
    node c={1,&d,&e};
    node b={-1,NULL,NULL};
    node a={1,&c,&b};
    tree v;
    v=&a;
    printf("%d\n",sumAt(v,3));
    return 0;
}

我尝试在每个级别打印 i 的值,但它也给出了一个错误,所以我不知道,我也尝试询问 Copilot 和 Gemini,但他们没有帮助

c data-structures binary-tree
1个回答
0
投票

在函数内

sumAtBis

int sumAtBis(tree a, int n, int i){
    if(i==n){
        if(isEmpty(a))
            return 0;
        else
            return root(a);
    }
    return sumAtBis(left(a),n,i+1)+sumAtBis(right(a),n,i+1);
    
}

不检查

left( a )
right( a )
是否为空指针。因此该函数可以调用未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.