What is the problem in my "sumAtBis" code?

46 views Asked by At

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

1

There are 1 answers

2
Vlad from Moscow On

Within the function 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);
    
}

there is no check whether left( a ) or right( a ) are null pointers. So the function can invoke undefined behavior.

Actually the function sumAtBis is redundant. It is enough to define the function sumAt as for example

long long int sumAt( tree a, size_t n )
{
    if ( isEmpty( a ) )
    {
        return 0;
    }
    else
    {
        return n == 0 ? 
            root( a ) : 
            sumAt( left( a ), n - 1 ) + sumAt( right( a ), n - 1 );
    }
}

And correspondingly the call of printf will look like

printf( "%lld\n", sumAt( v, n ) );
         ^^^^

Also using the typedef name tree

typedef node * tree;

is not a good idea because you can not define the type const node * by means of this typedef name because const tree is equivalent to node * const instead of the required type const node * and this type should be used in the parameter declaration of the function because the function does not change nodes of the tree.