hi
i'm trying to write a c code that calculates the sum of the leaves(only leaves) in a binary tree using recursion but its no worked out to me
please help me if you can
You mean it just closes?
The problem shouldn't be in this function, so we'll need to see more code (dont forget the code tags, the <> icon to the right).
typedefstruct Tree
{
int key;
struct Tree* left;
struct Tree* right;
}Tree;
int sumOfLeaves(Tree* root)
{
if(root->left == NULL && root->right ==NULL)
return root->key;
return sumOfLeaves(root->left) + sumOfLeaves(root->right)
}
int main
{
Tree* t = createTree(8); //function to create tree
addToTree(10,t);
addToTree(16,t); //adding numbers to the nodes of tree
addToTree(2,t);
addToTree(6,t);
addToTree(9,t);
addToTree(5,t);
printf("Sum: %d",sumOfLeaves(t)); //this should print the sum of leaves
return 0;
it's looks fine but when i run it its just give me a runtime error and close
i tried to debug it but i cant find the problem.
You should put that back in, because with it there are only two states that really matter, both children for a root is null, or they're not (which means both or one is not null). If they're both null you just return the value of the root, if they're not you call sumOfLeaves recursively, and if one of the children happens to be null you just return a 0.