i am here to ask about the problem about this function that calculates the sum at a given depth in a tree, it is working in all cases but the last level, the compiler is giving me this :
[Done] exited with code=3221225477 in 0.309 seconds
and this is my code and everything you need(there is more other functions and stuff but i think this is enough):
#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 tried printing the value of i at each level when but it also gives an error so i can't know, also i tried to ask Copilot and Gemini but they didn't help
Within the function
sumAtBisthere is no check whether
left( a )orright( a )are null pointers. So the function can invoke undefined behavior.Actually the function
sumAtBisis redundant. It is enough to define the functionsumAtas for exampleAnd correspondingly the call of
printfwill look likeAlso using the typedef name
treeis not a good idea because you can not define the type
const node *by means of this typedef name becauseconst treeis equivalent tonode * constinstead of the required typeconst node *and this type should be used in the parameter declaration of the function because the function does not change nodes of the tree.